Drupal 8's move to use Symfony2 components will bring many changes for Drupal developers as well as a steep learning curve. This talk aims to ease that process by giving a high level introduction to the Symfony2 framework.
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Introduction to Symfony2 for Drupal Developers
1. Introduction to Symfony2Introduction to Symfony2
Easing the learning curve for Drupal DevsEasing the learning curve for Drupal Devs
Drupal Waterloo Group, 16Drupal Waterloo Group, 16thth
May 2013May 2013
2. Tl;Dr: About meTl;Dr: About me
●
Ex-pat Englishman now living in SouthernEx-pat Englishman now living in Southern
Ontario.Ontario.
●
PHP developer for 5 years, Symfony 1 and 2PHP developer for 5 years, Symfony 1 and 2
user for just over a year.user for just over a year.
●
Senior Developer at MRX Digital SportsSenior Developer at MRX Digital Sports
Solutions.Solutions.
●
Co-organiserCo-organiser of Guelph PHP User Group.of Guelph PHP User Group.
●
Ex-professional musician.Ex-professional musician.
3. Drupal times they are a-changin!Drupal times they are a-changin!
●
Move to using Symfony components bringsMove to using Symfony components brings
many changes to Drupal.many changes to Drupal.
●
This talk aims to ease the learning curve.This talk aims to ease the learning curve.
●
Structure:Structure:
●
Introduction to Symfony2 architectureIntroduction to Symfony2 architecture
●
In depth look at the HttpKernelIn depth look at the HttpKernel
●
Introduction to other components that Drupal will beIntroduction to other components that Drupal will be
using.using.
5. Introduction to Symfony2Introduction to Symfony2
●
Application framework by Fabien Potencier andApplication framework by Fabien Potencier and
Sensio Labs.Sensio Labs.
●
Heavily inspired by other frameworks, includingHeavily inspired by other frameworks, including
Rails, Django and Spring.Rails, Django and Spring.
●
'Modern', object oriented code base, full test'Modern', object oriented code base, full test
coverage.coverage.
●
Emphasis on caching for speed.Emphasis on caching for speed.
6. Symfony2 Design GoalsSymfony2 Design Goals
●
Less MVC, more HTTP.Less MVC, more HTTP.
●
Don't re-invent the wheel.Don't re-invent the wheel.
●
De-coupled components:De-coupled components:
●
All code must be SOLIDAll code must be SOLID
●
Bundles.Bundles.
7. Less MVC, More HTTPLess MVC, More HTTP
●
Designed around the HTTP spec.Designed around the HTTP spec.
●
Purpose: convert a Request object into aPurpose: convert a Request object into a
Response.Response.
●
Model and (to a large part) the view layers areModel and (to a large part) the view layers are
left up to the user to implement.left up to the user to implement.
8. Don't Re-invent the WheelDon't Re-invent the Wheel
●
Symfony uses third party components whereSymfony uses third party components where
possible.possible.
●
Examples:Examples:
●
TwigTwig
●
SwiftmailerSwiftmailer
●
MonologMonolog
●
Doctrine/PropelDoctrine/Propel
●
AsseticAssetic
●
ComposerComposer
9. De-coupled ComponentsDe-coupled Components
●
The whole framework is a collection of de-The whole framework is a collection of de-
coupled components.coupled components.
●
Each component is (largely) independent of theEach component is (largely) independent of the
others.others.
●
Code adheres to SOLID principles.Code adheres to SOLID principles.
●
Enables components to be used in isolation inEnables components to be used in isolation in
other projects such as Drupal.other projects such as Drupal.
10. BundlesBundles
●
Bundle is a collection of related code, alsoBundle is a collection of related code, also
containing tests, assets, documentation andcontaining tests, assets, documentation and
config for that code.config for that code.
●
The Symfony2 framework is a bundle.The Symfony2 framework is a bundle.
●
Allows code to be easily shared and reused.Allows code to be easily shared and reused.
●
Healthy eco-system of shared bundlesHealthy eco-system of shared bundles
available on Packagist.available on Packagist.
11. Anatomy of a Symfony RequestAnatomy of a Symfony Request
How a Request is converted to a Response.
12. The Front ControllerThe Front Controller
●
Symfony2 uses the front controller pattern asSymfony2 uses the front controller pattern as
single entry point to application.single entry point to application.
●
Steps:Steps:
●
Includes cache files.Includes cache files.
●
Creates a Request and AppKernel objects.Creates a Request and AppKernel objects.
●
AppKernel::handle() method returns a responseAppKernel::handle() method returns a response
from the request.from the request.
●
Response::send() is called.Response::send() is called.
●
AppKernel::terminate() is then called.AppKernel::terminate() is then called.
13. The HttpKernelThe HttpKernel
●
Used to convert the request into a response.Used to convert the request into a response.
●
Created and called in the AppKernel.Created and called in the AppKernel.
●
An event dispatcher and controller resolver areAn event dispatcher and controller resolver are
passed to the constructor, the request object ispassed to the constructor, the request object is
passed to the handle method.passed to the handle method.
●
Event driven.Event driven.
15. The kernel.request eventThe kernel.request event
●
Used to initialise the system, add more info toUsed to initialise the system, add more info to
the request, etc.the request, etc.
●
If this event returns a response the kernel skipsIf this event returns a response the kernel skips
directly to the kernel.response event.directly to the kernel.response event.
●
Examples:Examples:
●
Security listeners are dispatched at this stage.Security listeners are dispatched at this stage.
●
Router listener.Router listener.
●
MRX sport listener for our API.MRX sport listener for our API.
16. Resolve ControllerResolve Controller
●
The controller resolver is used to get theThe controller resolver is used to get the
controller for the request.controller for the request.
●
Class implementing ControllerResolverInterfaceClass implementing ControllerResolverInterface
is passed to the HttpKernel in the constructor.is passed to the HttpKernel in the constructor.
●
Default implementation in Symfony2 willDefault implementation in Symfony2 will
instantiate the controller and, optionally, set theinstantiate the controller and, optionally, set the
container in it.container in it.
17. The kernel.controller eventThe kernel.controller event
●
Allows you to initialise the controller or changeAllows you to initialise the controller or change
it before the before it's executed.it before the before it's executed.
●
Can change the controller by setting a newCan change the controller by setting a new
controller on the event object.controller on the event object.
●
Example:Example:
●
SensioFrameworkExtra bundle ParamConverter.SensioFrameworkExtra bundle ParamConverter.
18. Getting Controller ArgumentsGetting Controller Arguments
●
ControllerResolverInterface::getArguments()ControllerResolverInterface::getArguments()
now called.now called.
●
Assembles array of arguments to pass to theAssembles array of arguments to pass to the
controller.controller.
●
Uses reflection.Uses reflection.
●
Default sf2 controller resolver:Default sf2 controller resolver:
●
Will match named arguments in the controllerWill match named arguments in the controller
method to attributes stored in the request object.method to attributes stored in the request object.
●
Will pass the request itself to the controller if it'sWill pass the request itself to the controller if it's
type hinted.type hinted.
19. Calling the controllerCalling the controller
●
Controller method is called with the argumentsController method is called with the arguments
assembled.assembled.
●
Controller must return a Response object or anController must return a Response object or an
array.array.
●
If a response is returned, kernels work is prettyIf a response is returned, kernels work is pretty
much done.much done.
●
If an array is returned another event isIf an array is returned another event is
dispatched...dispatched...
20. The kernel.view eventThe kernel.view event
●
Only dispatched if the controllerOnly dispatched if the controller doesn'tdoesn't returnreturn
a response object.a response object.
●
Job is to convert return data from controller to aJob is to convert return data from controller to a
response object.response object.
●
No default listeners in Symfony but examples:No default listeners in Symfony but examples:
●
SensioFrameworkExtraBundle adds listener forSensioFrameworkExtraBundle adds listener for
@Template annotations.@Template annotations.
●
FOSRestBundle adds a listener here to renderFOSRestBundle adds a listener here to render
XML, JSON or HTMLXML, JSON or HTML
21. The kernel.response eventThe kernel.response event
●
Called just before the response is returned.Called just before the response is returned.
●
Allows the response to be modified, e.g. settingAllows the response to be modified, e.g. setting
cookies, headers, etc.cookies, headers, etc.
●
Examples:Examples:
●
In the dev environment theIn the dev environment the
WebDebugToolbarListener adds some data toWebDebugToolbarListener adds some data to
enable the debugging toolbar.enable the debugging toolbar.
●
ContextListener serializes the current users info intoContextListener serializes the current users info into
the session.the session.
22. Almost done...Almost done...
●
The response is now returned from theThe response is now returned from the
HttpKernel.HttpKernel.
●
Response::send() is called to send the contentResponse::send() is called to send the content
to the client.to the client.
●
One more event will still be dispatched...One more event will still be dispatched...
23. The kernel.terminate eventThe kernel.terminate event
●
The only event called afterThe only event called after
HttpKernel::handle().HttpKernel::handle().
●
Used after the response has been sent toUsed after the response has been sent to
perform some 'heavy' action.perform some 'heavy' action.
●
Use with caution!Use with caution!
●
Example:Example:
●
SwiftmailerBundle with memory spooling.SwiftmailerBundle with memory spooling.
24. The kernel.exception eventThe kernel.exception event
●
Called if an uncaught exception is thrown.Called if an uncaught exception is thrown.
●
Used to handle some kinds of exceptions andUsed to handle some kinds of exceptions and
to create a response.to create a response.
●
Calls a special controller that generates anCalls a special controller that generates an
error page from the exception.error page from the exception.
●
Example:Example:
●
Throwing an exception that implementsThrowing an exception that implements
HttpExceptionInterface allows errors to beHttpExceptionInterface allows errors to be
converted to the correct HTTP response code.converted to the correct HTTP response code.
27. HttpFoundationHttpFoundation
●
Collection of classes for working with HTTPCollection of classes for working with HTTP
requests and responses.requests and responses.
●
Replaces PHP auto globals with an OOP layer.Replaces PHP auto globals with an OOP layer.
●
Four main 'areas':Four main 'areas':
●
RequestRequest
●
ResponseResponse
●
SessionSession
●
FileFile
28. The Request ClassThe Request Class
●
Contains request dataContains request data
(obviously)(obviously)
●
Has a series ofHas a series of
parameter bagsparameter bags
properties containingproperties containing
request data.request data.
●
These are:These are:
●
Request ($_POST)Request ($_POST)
●
Query ($_GET)Query ($_GET)
●
CookiesCookies
●
Attributes (used byAttributes (used by
the app to store data)the app to store data)
●
Files ($_FILESFiles ($_FILES
●
Server ($_SERVER)Server ($_SERVER)
●
Headers (sub-set ofHeaders (sub-set of
$_SERVER)$_SERVER)
29. The Response ClassThe Response Class
●
Actually a collection of classes.Actually a collection of classes.
●
Contains a large collection of setters/getters forContains a large collection of setters/getters for
manipulating all parts of the response.manipulating all parts of the response.
●
Many setters for working with the HTTP cache.Many setters for working with the HTTP cache.
●
From within a controller easiest way toFrom within a controller easiest way to
generate a response is to call thegenerate a response is to call the
Controller::render() method.Controller::render() method.
30. Session ManagementSession Management
●
Powerful, OOP wrapper around PHP's nativePowerful, OOP wrapper around PHP's native
session handling.session handling.
●
Contains a number of methods such as set(),Contains a number of methods such as set(),
get() and has() for working with session data.get() and has() for working with session data.
●
Flash messages.Flash messages.
●
Various session save handlers for working withVarious session save handlers for working with
different session storage mediums.different session storage mediums.
31. RoutingRouting
●
Routing consists of three main parts:Routing consists of three main parts:
●
A RouteCollection of Route objects.A RouteCollection of Route objects.
●
A RequestContext object.A RequestContext object.
●
A UrlMatcher object.A UrlMatcher object.
32. The RouteCollectionThe RouteCollection
●
Container for the routes available in anContainer for the routes available in an
application.application.
●
Each route added to the collection has a nameEach route added to the collection has a name
and a Route object.and a Route object.
33. The Route ObjectThe Route Object
●
Contains up to seven parts:Contains up to seven parts:
●
A URL route to match (may contain placeholders)A URL route to match (may contain placeholders)
●
Array of default values to return when the route isArray of default values to return when the route is
matched (i.e. 'controller' => 'foo')matched (i.e. 'controller' => 'foo')
●
Requirements array, such as constraints forRequirements array, such as constraints for
placeholders.placeholders.
●
Array of options (not commonly used)Array of options (not commonly used)
●
Optional host to match the route against.Optional host to match the route against.
●
Array of schemes (http, https, etc)Array of schemes (http, https, etc)
●
Array of valid http methodsArray of valid http methods
34. The RequestContextThe RequestContext
●
Contains information about the request.Contains information about the request.
●
Parameters passed to the constructor of thisParameters passed to the constructor of this
class.class.
●
If using Request object can pass that via theIf using Request object can pass that via the
RequestContext::fromRequest() methodRequestContext::fromRequest() method
instead.instead.
35. The UrlMatcherThe UrlMatcher
●
Given a route collection and a request context,Given a route collection and a request context,
tries to find a route that matches the requesttries to find a route that matches the request
URI.URI.
●
Can also be used to generate URL's in yourCan also be used to generate URL's in your
controllers or templates.controllers or templates.
36. The Event Dispatcher ComponentThe Event Dispatcher Component
●
Implementation of the Observer pattern.Implementation of the Observer pattern.
●
Central to the HttpKernel.Central to the HttpKernel.
●
Allows listeners to be notified in order when anAllows listeners to be notified in order when an
event is dispatched.event is dispatched.
●
Three main parts:Three main parts:
●
The event dispatcher.The event dispatcher.
●
Listeners to events.Listeners to events.
●
Event obects.Event obects.
37. The Event DispatcherThe Event Dispatcher
●
The addListener() method is used to add aThe addListener() method is used to add a
listener to an event.listener to an event.
●
Up to three arguments:Up to three arguments:
●
The name of the event.The name of the event.
●
A PHP callable to be dispatched.A PHP callable to be dispatched.
●
An optional priority.An optional priority.
38. The Event ListenerThe Event Listener
●
Nothing special here!Nothing special here!
●
Each callable is passed the event object whenEach callable is passed the event object when
called.called.
●
If you want to create an object that subscribesIf you want to create an object that subscribes
to multiple events use theto multiple events use the
EventSubscriberInterface.EventSubscriberInterface.
39. The Event ObjectThe Event Object
●
Basic event object has 2 methods:Basic event object has 2 methods:
●
isPropagationStopped()isPropagationStopped()
●
stopPropagation()stopPropagation()
●
Designed to be extended by you!Designed to be extended by you!
●
After each listener is called the dispatcherAfter each listener is called the dispatcher
checks if propagation has been stopped.checks if propagation has been stopped.
41. A bit of background...A bit of background...
●
DI is one of the SOLID guidelines.DI is one of the SOLID guidelines.
●
Helps to ensure that code is loosely coupled.Helps to ensure that code is loosely coupled.
●
Also enables the Liskov substitution principle.Also enables the Liskov substitution principle.
●
Makes unit testing much easier.Makes unit testing much easier.
●
In general, if your class has '$foo = new Bar'In general, if your class has '$foo = new Bar'
you're doing it wrong.you're doing it wrong.
42. How do all of these objects getHow do all of these objects get
made?made?
43. Enter the DI ContainerEnter the DI Container
●
An object that knows how to make otherAn object that knows how to make other
objects.objects.
●
Objects made as needed.Objects made as needed.
●
Fetching an object is as simple as callingFetching an object is as simple as calling
Container::get('name')Container::get('name')
●
Call pass arguments to methods.Call pass arguments to methods.
●
Service Locator or DI Container?Service Locator or DI Container?
44. Configuring the ContainerConfiguring the Container
●
ParametersParameters
●
Values to be passed to other objects.Values to be passed to other objects.
●
Easily reusableEasily reusable
●
ServicesServices
●
Objects managed by the containerObjects managed by the container
●
Registered by nameRegistered by name
●
Allows constructor injection, setter injection andAllows constructor injection, setter injection and
setting public properties on the service.setting public properties on the service.
●
Can pass other services as arguments to methods.Can pass other services as arguments to methods.
45. Tagged ServicesTagged Services
●
Services can be tagged with meta data.Services can be tagged with meta data.
●
Doesn't alter service definition but the containerDoesn't alter service definition but the container
can retrieve services by tag name.can retrieve services by tag name.
●
Example:Example:
●
Tagging a service with the name of an event, anTagging a service with the name of an event, an
event name and a method to call. Allows it to beevent name and a method to call. Allows it to be
called with the event dispatcher.called with the event dispatcher.
46. Questions?Questions?
●
Feel free to contact me with any questions orFeel free to contact me with any questions or
comments:comments:
●
jeremycook0@gmail.comjeremycook0@gmail.com
●
@JCook21@JCook21
●
http://jeremycook.cahttp://jeremycook.ca
●
Thanks for listening.Thanks for listening.
Hinweis der Redaktion
Note that Symfony2 often described as an HTTP framework. Mention how the HttpKernel converts the request to a response. Mention that Symfony has a view component in PHP and that Twig can also be used, but that this can be replaced with any other view that you like. Response doesn't need to be HTML!
Mention that this is the opposite of, for example, Zend Framework. A lot of these tools are bundled into the Symfony standard edition but you can use any others that you wish.
Mention design by contract. SOLID Single Responsibility Principle Open/closed principle Liskov substitution principle. Interface Segregation principle. Dependency inversion principle. Other projects built with Symfony2 components: Laravel Silex React
Mention app.php and app_dev.php as entry points to application. Terminate method used as a place to process long running tasks after the response has been sent to the browser for the user. USE WITH CARE.
Explain how the event system works here. Observer pattern. Allows you to create your own observers that are attached and dispatched with events.
Mention that attributes can be stored on the request to be used later. Router listener will store a _controller key on the request to use later.
Explain how param converters used.
Mention that sf2 has default templates for different HTTP errors. These can be overridden.
Mention that in addition to response there are specialised response classes like JsonResponse, BinaryFileResponse, RedirectResponse, etc. Controllers render method accepts a template name, an array of params and an optional response object.
Mention what flash messages are and. Explain that the session object stores the flash messages in a 'FlashBag' class.
Mention that URL's are generated by passing the route name and an array of parameters. Very handy if the URL's change as nothing needs to change in the controllers or views.
Explain how you might want to use events: Separation of concerns. Extension points for applications. Easy code reusability. Bad point: makes it harder to find/see what's going on.
Mention that higher priority means dispatched first. Priority defaults to 0. If two callbacks have the same priority then dispatched in order they're added.
Mention that the EventSubscriberInterface notifies the dispatcher what events it listens to. Call addSubscriber() method on the dispatcher to add a subscriber.
Mention that the event object is available in the scope after being dispatched. Therefore it can hold the results of the event dispatch.
Note that the name of a service is what it is referred to when you want to fetch an instance.