• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Introduction to Symfony2 for Drupal Developers
 

Introduction to Symfony2 for Drupal Developers

on

  • 938 views

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 ...

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.

Statistics

Views

Total Views
938
Views on SlideShare
938
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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.

Introduction to Symfony2 for Drupal Developers Introduction to Symfony2 for Drupal Developers Presentation Transcript

  • Introduction to Symfony2Introduction to Symfony2Easing the learning curve for Drupal DevsEasing the learning curve for Drupal DevsDrupal Waterloo Group, 16Drupal Waterloo Group, 16ththMay 2013May 2013
  • Tl;Dr: About meTl;Dr: About me●Ex-pat Englishman now living in SouthernEx-pat Englishman now living in SouthernOntario.Ontario.●PHP developer for 5 years, Symfony 1 and 2PHP developer for 5 years, Symfony 1 and 2user for just over a year.user for just over a year.●Senior Developer at MRX Digital SportsSenior Developer at MRX Digital SportsSolutions.Solutions.●Co-organiserCo-organiser of Guelph PHP User Group.of Guelph PHP User Group.●Ex-professional musician.Ex-professional musician.
  • Drupal times they are a-changin!Drupal times they are a-changin!●Move to using Symfony components bringsMove to using Symfony components bringsmany 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 beusing.using.
  • In the beginning...In the beginning...Introduction to Symfony2
  • Introduction to Symfony2Introduction to Symfony2●Application framework by Fabien Potencier andApplication framework by Fabien Potencier andSensio Labs.Sensio Labs.●Heavily inspired by other frameworks, includingHeavily inspired by other frameworks, includingRails, Django and Spring.Rails, Django and Spring.●Modern, object oriented code base, full testModern, object oriented code base, full testcoverage.coverage.●Emphasis on caching for speed.Emphasis on caching for speed.
  • Symfony2 Design GoalsSymfony2 Design Goals●Less MVC, more HTTP.Less MVC, more HTTP.●Dont re-invent the wheel.Dont re-invent the wheel.●De-coupled components:De-coupled components:●All code must be SOLIDAll code must be SOLID●Bundles.Bundles.
  • 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 aResponse.Response.●Model and (to a large part) the view layers areModel and (to a large part) the view layers areleft up to the user to implement.left up to the user to implement.
  • Dont Re-invent the WheelDont Re-invent the Wheel●Symfony uses third party components whereSymfony uses third party components wherepossible.possible.●Examples:Examples:●TwigTwig●SwiftmailerSwiftmailer●MonologMonolog●Doctrine/PropelDoctrine/Propel●AsseticAssetic●ComposerComposer
  • 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 theothers.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 inother projects such as Drupal.other projects such as Drupal.
  • BundlesBundles●Bundle is a collection of related code, alsoBundle is a collection of related code, alsocontaining tests, assets, documentation andcontaining tests, assets, documentation andconfig 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 bundlesavailable on Packagist.available on Packagist.
  • Anatomy of a Symfony RequestAnatomy of a Symfony RequestHow a Request is converted to a Response.
  • The Front ControllerThe Front Controller●Symfony2 uses the front controller pattern asSymfony2 uses the front controller pattern assingle 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 responsefrom the request.from the request.●Response::send() is called.Response::send() is called.●AppKernel::terminate() is then called.AppKernel::terminate() is then called.
  • 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 arepassed to the constructor, the request object ispassed to the constructor, the request object ispassed to the handle method.passed to the handle method.●Event driven.Event driven.
  • Anatomy of HttpKernelAnatomy of HttpKernel
  • The kernel.request eventThe kernel.request event●Used to initialise the system, add more info toUsed to initialise the system, add more info tothe request, etc.the request, etc.●If this event returns a response the kernel skipsIf this event returns a response the kernel skipsdirectly 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.
  • Resolve ControllerResolve Controller●The controller resolver is used to get theThe controller resolver is used to get thecontroller for the request.controller for the request.●Class implementing ControllerResolverInterfaceClass implementing ControllerResolverInterfaceis passed to the HttpKernel in the constructor.is passed to the HttpKernel in the constructor.●Default implementation in Symfony2 willDefault implementation in Symfony2 willinstantiate the controller and, optionally, set theinstantiate the controller and, optionally, set thecontainer in it.container in it.
  • The kernel.controller eventThe kernel.controller event●Allows you to initialise the controller or changeAllows you to initialise the controller or changeit before the before its executed.it before the before its executed.●Can change the controller by setting a newCan change the controller by setting a newcontroller on the event object.controller on the event object.●Example:Example:●SensioFrameworkExtra bundle ParamConverter.SensioFrameworkExtra bundle ParamConverter.
  • 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 thecontroller.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 controllermethod to attributes stored in the request object.method to attributes stored in the request object.●Will pass the request itself to the controller if itsWill pass the request itself to the controller if itstype hinted.type hinted.
  • Calling the controllerCalling the controller●Controller method is called with the argumentsController method is called with the argumentsassembled.assembled.●Controller must return a Response object or anController must return a Response object or anarray.array.●If a response is returned, kernels work is prettyIf a response is returned, kernels work is prettymuch done.much done.●If an array is returned another event isIf an array is returned another event isdispatched...dispatched...
  • The kernel.view eventThe kernel.view event●Only dispatched if the controllerOnly dispatched if the controller doesntdoesnt returnreturna response object.a response object.●Job is to convert return data from controller to aJob is to convert return data from controller to aresponse 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 renderXML, JSON or HTMLXML, JSON or HTML
  • 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. settingcookies, headers, etc.cookies, headers, etc.●Examples:Examples:●In the dev environment theIn the dev environment theWebDebugToolbarListener adds some data toWebDebugToolbarListener adds some data toenable the debugging toolbar.enable the debugging toolbar.●ContextListener serializes the current users info intoContextListener serializes the current users info intothe session.the session.
  • Almost done...Almost done...●The response is now returned from theThe response is now returned from theHttpKernel.HttpKernel.●Response::send() is called to send the contentResponse::send() is called to send the contentto the client.to the client.●One more event will still be dispatched...One more event will still be dispatched...
  • The kernel.terminate eventThe kernel.terminate event●The only event called afterThe only event called afterHttpKernel::handle().HttpKernel::handle().●Used after the response has been sent toUsed after the response has been sent toperform some heavy action.perform some heavy action.●Use with caution!Use with caution!●Example:Example:●SwiftmailerBundle with memory spooling.SwiftmailerBundle with memory spooling.
  • 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 andto create a response.to create a response.●Calls a special controller that generates anCalls a special controller that generates anerror page from the exception.error page from the exception.●Example:Example:●Throwing an exception that implementsThrowing an exception that implementsHttpExceptionInterface allows errors to beHttpExceptionInterface allows errors to beconverted to the correct HTTP response code.converted to the correct HTTP response code.
  • Questions so far?Questions so far?Time for a breather!
  • Components being used in Drupal.Components being used in Drupal.
  • HttpFoundationHttpFoundation●Collection of classes for working with HTTPCollection of classes for working with HTTPrequests 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
  • The Request ClassThe Request Class●Contains request dataContains request data(obviously)(obviously)●Has a series ofHas a series ofparameter bagsparameter bagsproperties containingproperties containingrequest data.request data.●These are:These are:●Request ($_POST)Request ($_POST)●Query ($_GET)Query ($_GET)●CookiesCookies●Attributes (used byAttributes (used bythe 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)
  • 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 formanipulating 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 togenerate a response is to call thegenerate a response is to call theController::render() method.Controller::render() method.
  • Session ManagementSession Management●Powerful, OOP wrapper around PHPs nativePowerful, OOP wrapper around PHPs nativesession 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 withdifferent session storage mediums.different session storage mediums.
  • 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.
  • The RouteCollectionThe RouteCollection●Container for the routes available in anContainer for the routes available in anapplication.application.●Each route added to the collection has a nameEach route added to the collection has a nameand a Route object.and a Route object.
  • 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 ismatched (i.e. controller => foo)matched (i.e. controller => foo)●Requirements array, such as constraints forRequirements array, such as constraints forplaceholders.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
  • 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 thisclass.class.●If using Request object can pass that via theIf using Request object can pass that via theRequestContext::fromRequest() methodRequestContext::fromRequest() methodinstead.instead.
  • 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 requestURI.URI.●Can also be used to generate URLs in yourCan also be used to generate URLs in yourcontrollers or templates.controllers or templates.
  • 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 anevent 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.
  • The Event DispatcherThe Event Dispatcher●The addListener() method is used to add aThe addListener() method is used to add alistener 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.
  • 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 whencalled.called.●If you want to create an object that subscribesIf you want to create an object that subscribesto multiple events use theto multiple events use theEventSubscriberInterface.EventSubscriberInterface.
  • 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 dispatcherchecks if propagation has been stopped.checks if propagation has been stopped.
  • The Dependency InjectionThe Dependency InjectionContainerContainer
  • 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 BarIn general, if your class has $foo = new Baryoure doing it wrong.youre doing it wrong.
  • How do all of these objects getHow do all of these objects getmade?made?
  • Enter the DI ContainerEnter the DI Container●An object that knows how to make otherAn object that knows how to make otherobjects.objects.●Objects made as needed.Objects made as needed.●Fetching an object is as simple as callingFetching an object is as simple as callingContainer::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?
  • 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 andsetting 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.
  • Tagged ServicesTagged Services●Services can be tagged with meta data.Services can be tagged with meta data.●Doesnt alter service definition but the containerDoesnt alter service definition but the containercan 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, anevent name and a method to call. Allows it to beevent name and a method to call. Allows it to becalled with the event dispatcher.called with the event dispatcher.
  • Questions?Questions?●Feel free to contact me with any questions orFeel free to contact me with any questions orcomments:comments:●jeremycook0@gmail.comjeremycook0@gmail.com●@JCook21@JCook21●http://jeremycook.cahttp://jeremycook.ca●Thanks for listening.Thanks for listening.