Silex is a PHP microframework built on Symfony2 and Pimple. This document provides an introduction to Silex by demonstrating how to set up a basic application with routing and Twig templating. It then expands on this by implementing an API with CRUD endpoints for users using Doctrine DBAL and MySQL. Finally, it discusses advanced topics like extending the application class, separating configuration and routes, and using request lifecycle hooks.
Everyone knows that Silex is a great microframework for APIs and small sites, but what do you do when you want to build a large site, or your little tiny site has grown up? Silex has many different ways to let you build larger, complex websites that might still be too small for Symfony, but have outgrown the single page app it once was. We’ll look at what Silex offers us, and different ways we can structure our site.
Keeping it small - Getting to know the Slim PHP micro frameworkJeremy Kendall
Learn what the big deal is about PHP micro frameworks by taking a tour through an application written in Slim PHP. I'll briefly introduce you to some high level concepts, show how those concepts can be implemented in Slim, and see how powerful and elegant micro framework can be.
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Arc & Codementor
Codementor PHP expert mentor Ben Edmunds is the co-host of PHP Town Hall and author of Building Secure PHP Apps.
Ben is also the creator of Ion Auth, a simple, lightweight authentication library for CodeIgniter.
In an interactive format, Ben talked about:
Modern PHP
Latest PHP tools
SQL Injection
Password Hashing and Authentication
Other Common Hacks
https://www.codementor.io/benedmunds
https://www.codementor.io/php-tutorial/building-modern-secure-php-applications-codementor-office-hours-ben-edmunds
Everyone knows that Silex is a great microframework for APIs and small sites, but what do you do when you want to build a large site, or your little tiny site has grown up? Silex has many different ways to let you build larger, complex websites that might still be too small for Symfony, but have outgrown the single page app it once was. We’ll look at what Silex offers us, and different ways we can structure our site.
Keeping it small - Getting to know the Slim PHP micro frameworkJeremy Kendall
Learn what the big deal is about PHP micro frameworks by taking a tour through an application written in Slim PHP. I'll briefly introduce you to some high level concepts, show how those concepts can be implemented in Slim, and see how powerful and elegant micro framework can be.
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Arc & Codementor
Codementor PHP expert mentor Ben Edmunds is the co-host of PHP Town Hall and author of Building Secure PHP Apps.
Ben is also the creator of Ion Auth, a simple, lightweight authentication library for CodeIgniter.
In an interactive format, Ben talked about:
Modern PHP
Latest PHP tools
SQL Injection
Password Hashing and Authentication
Other Common Hacks
https://www.codementor.io/benedmunds
https://www.codementor.io/php-tutorial/building-modern-secure-php-applications-codementor-office-hours-ben-edmunds
Building Single Page Application (SPA) with Symfony2 and AngularJSAntonio Peric-Mazar
Forget about classic website where UX is not so important. We are living in time where usability is one of the important thing if you are building some business client oriented web service. How to connect Symfony2 as backend and AngularJS as frontend solution? What are best practices? What are disadvantageous? How to take best from both worlds? These are topics I will cover in my talk with real examples.
Slides from the talk at http://www.meetup.com/GTA-PHP-User-Group-Toronto/events/151672182/
Source code for the demo at https://github.com/zymsys/Slim-RedBeanPHP-KnockoutJS
Like many others, WordPress has been my personal blogging tool for a long time. A powerful tool for easy publishing! That is what everyone wants.
Large sites like TechCrunch and TheNextWeb use it exactly for that reason. And more enterprises seem to discover it as good solution to their too-expensive publication tools. But keeping those WordPress instances running requires skills and knowledge.
Because of WordPress extendibility and its very active community, you can do this too. This tutorial will teach you how use Ansible, Composer, WP-CLI, WP REST API, and Elasticsearch can push WordPress from a personal blogging tool into an enterprise-worthy level application. Out with FTP based SCM ... in with automated deployment, dependency management, and utterly fast search.
These are my slide from talk at PHPDay in Verona 20014.
Forget about classic website where UX is not so important. We are living in time where usability is one of the important thing if you are building some business client oriented web service. In locastic we are working on CRM that is based on Symfony2 as backend and AngularJS as frontend solution.
How to connect this two frameworks? What are best practices? What are disadvantageous? How to take best from both worlds? These are topics I will cover in my talk with real examples.
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreRyan Weaver
There are so many interesting ways to authenticate a user: via an API token, social login, a traditional HTML form or anything else you can dream up.
But until now, creating a custom authentication system in Symfony has meant a lot of files and a lot of complexity.
Introducing Guard: a simple, but expandable authentication system built on top of Symfony's security component. Want to authenticate via an API token? Great - that's just one class. Social login? Easy! Have some crazy legacy central authentication system? In this talk, we'll show you how you'd implement any of these in your application today.
Don't get me wrong - you'll still need to do some work. But finally, the path will be clear and joyful.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Slides from the GTA-PHP meetup about the new features in PHP 7. Slides had corresponding RFC pages linked to them in the speaker notes, but they don't seem to correspond to pages here so I've made the original keynote file available at http://gtaphp.org/presentations/NewInPHP7.zip and a PowerPoint version at http://gtaphp.org/presentations/NewInPHP7.pptx.
Like many others, WordPress has been my personal blogging tool for a long time. A powerful tool for easy publishing! That is what everyone wants.
Large sites like TechCrunch and TheNextWeb use it exactly for that reason. And more enterprises seem to discover it as good solution to their too-expensive publication tools. But keeping those WordPress instances running requires skills and knowledge.
Because of WordPress extendibility and its very active community, you can do this too. This tutorial will teach you how use Ansible, Composer, WP-CLI, WP REST API, and Elasticsearch can push WordPress from a personal blogging tool into an enterprise-worthy level application. Out with FTP based SCM ... in with automated deployment, dependency management, and utterly fast search.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Building Single Page Application (SPA) with Symfony2 and AngularJSAntonio Peric-Mazar
Forget about classic website where UX is not so important. We are living in time where usability is one of the important thing if you are building some business client oriented web service. How to connect Symfony2 as backend and AngularJS as frontend solution? What are best practices? What are disadvantageous? How to take best from both worlds? These are topics I will cover in my talk with real examples.
Slides from the talk at http://www.meetup.com/GTA-PHP-User-Group-Toronto/events/151672182/
Source code for the demo at https://github.com/zymsys/Slim-RedBeanPHP-KnockoutJS
Like many others, WordPress has been my personal blogging tool for a long time. A powerful tool for easy publishing! That is what everyone wants.
Large sites like TechCrunch and TheNextWeb use it exactly for that reason. And more enterprises seem to discover it as good solution to their too-expensive publication tools. But keeping those WordPress instances running requires skills and knowledge.
Because of WordPress extendibility and its very active community, you can do this too. This tutorial will teach you how use Ansible, Composer, WP-CLI, WP REST API, and Elasticsearch can push WordPress from a personal blogging tool into an enterprise-worthy level application. Out with FTP based SCM ... in with automated deployment, dependency management, and utterly fast search.
These are my slide from talk at PHPDay in Verona 20014.
Forget about classic website where UX is not so important. We are living in time where usability is one of the important thing if you are building some business client oriented web service. In locastic we are working on CRM that is based on Symfony2 as backend and AngularJS as frontend solution.
How to connect this two frameworks? What are best practices? What are disadvantageous? How to take best from both worlds? These are topics I will cover in my talk with real examples.
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreRyan Weaver
There are so many interesting ways to authenticate a user: via an API token, social login, a traditional HTML form or anything else you can dream up.
But until now, creating a custom authentication system in Symfony has meant a lot of files and a lot of complexity.
Introducing Guard: a simple, but expandable authentication system built on top of Symfony's security component. Want to authenticate via an API token? Great - that's just one class. Social login? Easy! Have some crazy legacy central authentication system? In this talk, we'll show you how you'd implement any of these in your application today.
Don't get me wrong - you'll still need to do some work. But finally, the path will be clear and joyful.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Slides from the GTA-PHP meetup about the new features in PHP 7. Slides had corresponding RFC pages linked to them in the speaker notes, but they don't seem to correspond to pages here so I've made the original keynote file available at http://gtaphp.org/presentations/NewInPHP7.zip and a PowerPoint version at http://gtaphp.org/presentations/NewInPHP7.pptx.
Like many others, WordPress has been my personal blogging tool for a long time. A powerful tool for easy publishing! That is what everyone wants.
Large sites like TechCrunch and TheNextWeb use it exactly for that reason. And more enterprises seem to discover it as good solution to their too-expensive publication tools. But keeping those WordPress instances running requires skills and knowledge.
Because of WordPress extendibility and its very active community, you can do this too. This tutorial will teach you how use Ansible, Composer, WP-CLI, WP REST API, and Elasticsearch can push WordPress from a personal blogging tool into an enterprise-worthy level application. Out with FTP based SCM ... in with automated deployment, dependency management, and utterly fast search.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Silex is a brand new PHP 5.3 micro framework built on top of the Symfony2 de decoupled components. In this session, we will discover how to build and deploy powerful REST web services with such a micro framework and its embedded tools.
The first part of this talk will introduce the basics of the REST architecture. We fill focus on the main concepts of REST like HTTP methods, URIs and open formats like XML and JSON.
Then, we will discover how to deploy REST services using most of interesting Silex tools like database abstraction layer, template engine and input validation. We will also look at unit and functional testing frameworks with PHPUnit and HTTP caching with Edge Side Includes and Varnish support to improve performances.
Your Marketing Funnel is a Hot Mess - 8 Strategies for Improvement - check out the SlideShare presentation by Erin Sagin, PPC Evangelist & Community Manager at Wordstream and Michal Leszczynski, Content Marketing Manager at GetResponse.
You can access the webinar recording on GetResponseTV - http://bit.ly/GR-Funnel-Webinar
Standing on the shoulders of giants, Silex is a micro framework built on top of Symfony2 components. It provides an ideal environment for throwing together a simple, single file application. We’ll look at a real example of installing and setting up Silex and creating our first application with full dependency injection, templating and all the other features that you would expect of a modern day PHP framework. This session is recommended for anyone looking to break into the Symfony ecosystem with a simple introduction to a small framework build upon the core components of it’s bigger brother (Symfony2).
View how"out-of-the-box" thinkers David Skok and Mike Volpe define an optimized sales and marketing funnel; and describe how to identify problems and create long-lasting solutions for your organization during this complimentary one-hour online training session: http://www.hubspot.com/webinars/optimize-the-sales-and-marketing-funnel/
Each month, join us as we highlight and discuss hot topics ranging from the future of higher education to wearable technology, best productivity hacks and secrets to hiring top talent. Upload your SlideShares, and share your expertise with the world!
Not sure what to share on SlideShare?
SlideShares that inform, inspire and educate attract the most views. Beyond that, ideas for what you can upload are limitless. We’ve selected a few popular examples to get your creative juices flowing.
Sprockets is an easy solution to managing large JavaScript codebases by letting you structure it, bundle it with related assets, and consolidate it as one single file, with pre-baked command-line tooling, CGI front and Rails plugin. It's a framework-agnostic open-source solution that makes for great serving performance while helping you structure and manage your codebase better.
Keep hearing about Plack and PSGI, and not really sure what they're for, and why they're popular? Maybe you're using Plack at work, and you're still copying-and-pasting `builder` lines in to your code without really knowing what's going on? What's the relationship between Plack, PSGI, and CGI? Plack from first principles works up from how CGI works, the evolution that PSGI represents, and how Plack provides a user-friendly layer on top of that.
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
Presented at Railsconf 2015 by Daniel Spector, @danielspecs.
Crossing the Bridge explores tools, patterns and best practices to connect your Javascript MVC framework to Rails in the most seamless way possible. The talk progresses from demonstrating the standard API request cycle to preloading data to your client-side framework to rendering your javascript on the server. It explores Isomorphic Javascript and ways of implementing it with Rails.
A quick guide for setting up Appcelerator's Node.ACS and examples on how to build three different types of websites/APIs. Code can be found at:
https://github.com/ricardoalcocer/acs_key_value_store
https://github.com/ricardoalcocer/nodeacs_sample_website
A quick guide for setting up Appcelerator's Node.ACS and examples on how to build three different types of websites/APIs. Code can be found at:
https://github.com/ricardoalcocer/acs_key_value_store
https://github.com/ricardoalcocer/nodeacs_sample_website
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Ondřej Machulda
Annotated slides from Berlin PHP Usergroup Meetup, 4th April 2017.
---
Not only unit tests but also end-to-end tests in real browser are important part of test automation and test pyramid. So let's have a look how to easily write and run Selenium functional tests using PHPUnit and Steward.
In this talk, I'll show you how you can build Alfresco ADF applications using the new version 3.0.0. The new ADF versions include a number of new features and some breaking changes with the past that will make your life easier, I'll show you how to take advantage of it and embrace the change.
Introduction to Cocoapods as Dependency Management for iOS project using Swift. This slide will also introduce some of common library used in iOS Development: Alamofire, SwiftyJSON, MBProgressHUD.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
2. About me
I'm Chris Kemper
I work at Drummond Central, but I also freelance
I've been in the industry for around 5 years
I've written a book with a snake on the cover (It's on
Version Control, if you didn't know)
I also own an elePHPant
Sunday, 21 April 13
4. What is Silex?
"Silex is a PHP microframework for PHP 5.3. It is built on the
shoulders of Symfony2 and Pimple and also inspired by sinatra."
Created by Fabien Potencier and Igor Wiedler
Sunday, 21 April 13
5. Getting started
You can download it from the site directly
http://silex.sensiolabs.org/
Or, you can get with the times and use Composer
{
"require": {
"silex/silex": "1.0.*@dev"
! }
}
Sunday, 21 April 13
6. Your first end point
I’ve used Composer, so after it’s all installed, you can add the first end
point!
require_once __DIR__.'/../vendor/autoload.php';
$app = new SilexApplication();
$app->get('/hello/{name}', function($name) use($app) {
!return 'Hello '.$app->escape($name);
});
$app->run();
Sunday, 21 April 13
7. Don’t forget about .htaccess
Composer doesn’t pull it down, do don’t forget to put it in.
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
#RewriteBase /path/to/app
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
If you’re using Apache 2.2.16+, then you can use:
FallbackResource /index.php
Sunday, 21 April 13
9. Using a templating language
You don’t always want to output strings, so let’s use Twig, because it’s
awesome.
{
"require": {
"silex/silex": "1.0.*@dev",
"twig/twig": ">=1.8,<2.0-dev",
"symfony/twig-bridge": "~2.1"
}
}
Sunday, 21 April 13
10. Register the Twig Service provider
$app->register(new SilexProviderTwigServiceProvider(), array(
! 'twig.path' => __DIR__.'/views',
));
Now to use it
$app->get('/hello/{name}', function ($name) use ($app) {
!return $app['twig']->render('hello.twig', array(
! 'name' => $name,
));
});
Sunday, 21 April 13
11. So many more Service providers
Check the docs at http://silex.sensiolabs.org/documentation
There are a boat load of Built-in Service Providers which you can take advantage of!
Doctrine, Monolog, Form and Validation are just a couple of examples.
Sunday, 21 April 13
12. Tips: Extending the base application
This allows you to add, anything to the base application to
make your own life easier.
First of all, you need a class
<?php
namespace Acme;
use
SilexApplication as BaseApplication;
class Application extends BaseApplication {
}
Sunday, 21 April 13
13. Tips: Extending the base application
Now time to autoload that class, psr-0 style.
{
"require": {
"silex/silex": "1.0.*@dev",
"twig/twig": ">=1.8,<2.0-dev",
"symfony/twig-bridge": "~2.1"!
},
"autoload": {
"psr-0": {"Acme": "src/"}
}
}
Sunday, 21 April 13
14. Tips: Separate your config and routes
app/bootstrap.php
require_once __DIR__ . '/../vendor/autoload.php';
use
! SymfonyComponentHttpFoundationRequest,
! SymfonyComponentHttpFoundationResponse;
use
! AcmeApplication;
$app = new Application;
$app->register(new SilexProviderTwigServiceProvider(),
array(
! 'twig.path' => __DIR__.'/views',
));
return $app;
Sunday, 21 April 13
15. Tips: Separate your config and routes
web/index.php
<?php
$app = include __DIR__ . '/../app/bootstrap.php';
$app->get('/hello/{name}', function ($name) use ($app) {
return $app['twig']->render('hello.twig', array(
'name' => $name,
));
});
$app->run();
Sunday, 21 April 13
16. Let's make an API
Silex is great for API's, so let's make one. Here is the groundwork for a basic
user-based API
Some lovely endpoints:
Create a user (/user) - This will use POST to create a new user in the DB.
Update a user (/user/{id}) - This will use PUT to update the user
View a user (/user/{id}) - This will use GET to view the users information
Delete a user (/user/{id}) - Yes you guessed it, this uses the DELETE method.
Sunday, 21 April 13
17. More dependencies!
If we want to use a database, we'll need to define one. Let's get DBAL!
{
"require": {
"silex/silex": "1.0.*@dev",
"twig/twig": ">=1.8,<2.0-dev",
"symfony/twig-bridge": "~2.1",
"doctrine/dbal": "2.2.*"
},
"autoload": {
"psr-0": {"Acme": "src/"}
}
}
Sunday, 21 April 13
18. More dependencies!
It'll just be MySQL so let's configure that
$app->register(new DoctrineServiceProvider(), array(
! 'db.options' => array(
! ! 'dbname' ! => 'acme',
! ! 'user' ! ! => 'root',
! ! 'password' ! => 'root',
! ! 'host' ! ! => 'localhost',
! ! 'driver' ! => 'pdo_mysql',
! ),
));
Sunday, 21 April 13
19. Show me your endpoints: POST
Before we can do anything, we need to create some users.
$app->post('/user', function (Request $request) use ($app) {
$user = array(
'email' => $request->get('email'),
! 'name' => $request->get('name')
);
$app['db']->insert('user', $user);
return new Response("User " . $app['db']->lastInsertId() . "
created", 201);
});
Sunday, 21 April 13
20. Show me your endpoints: PUT
To update the users, we need to use PUT
$app->put('/user/{id}', function (Request $request, $id) use
($app) {
$sql = "UPDATE user SET email = ?, name = ? WHERE id = ?";
$app['db']->executeUpdate($sql, array(
$request->get('email'),
$request->get('name'),
(int) $id)
);
!
return new Response("User " . $id . " updated", 303);
});
Sunday, 21 April 13
21. Show me your endpoints: GET
Let's get the API to output the user data as JSON
$app->get('/user/{id}', function (Request $request, $id) use
($app) {
$sql = "SELECT * FROM user WHERE id = ?";
$post = $app['db']->fetchAssoc($sql, array((int) $id));
return $app->json($post, 201);
});
Sunday, 21 April 13
22. Show me your endpoints: DELETE
Lastly, we have DELETE
$app->delete('/user/{id}', function (Request $request, $id) use
($app) {
$sql = "DELETE FROM user WHERE id = ?";
$app['db']->executeUpdate($sql, array((int) $id));
return new Response("User " . $id . " deleted", 303);
});
Sunday, 21 April 13
23. A note about match()
Using match, you can catch any method used on a route. Like so:
$app->match('/user', function () use ($app) {
! ...
});
You can also limit the method accepted by match by using the 'method'
method
$app->match('/user', function () use ($app) {
! ...
})->method('PUT|POST');
Sunday, 21 April 13
24. Using before() and after()
Each request, can be pre, or post processed. In this case, it could be used for
auth.
$before = function (Request $request) use ($app) {
...
};
$after = function (Request $request) use ($app) {
...
};
$app->match('/user', function () use ($app) {
...
})
->before($before)
->after($after);
Sunday, 21 April 13
25. Using before() and after()
This can also be used globally, like so:
$app->before(function(Request $request) use ($app) {
...
});
You can also make an event be as early as possible, or as late as possible by
using Application::EARLY_EVENT and Application::LATE_EVENT, respectively.
$app->before(function(Request $request) use ($app) {
...
}, Application::EARLY_EVENT);
Sunday, 21 April 13
27. Summary
This is just a small amount of what Silex is capable
of, try it out.
Thank You!
http://silex.sensiolabs.org/
@chrisdkemper
http://chrisdkemper.co.uk
Sunday, 21 April 13