SlideShare ist ein Scribd-Unternehmen logo
1 von 46
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
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.
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.
In the beginning...In the beginning...
Introduction to Symfony2
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.
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.
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.
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
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.
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.
Anatomy of a Symfony RequestAnatomy of a Symfony Request
How a Request is converted to a Response.
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.
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.
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 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.
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.
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.
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.
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...
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
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.
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...
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.
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.
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 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
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)
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.
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.
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 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.
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
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.
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.
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.
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.
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.
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.
The Dependency InjectionThe Dependency Injection
ContainerContainer
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.
How do all of these objects getHow do all of these objects get
made?made?
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?
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.
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.
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.

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Kürzlich hochgeladen (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
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.
  • 4. In the beginning...In the beginning... Introduction to Symfony2
  • 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.
  • 25. Questions so far?Questions so far? Time for a breather!
  • 26. Components being used in Drupal.Components being used in Drupal.
  • 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.
  • 40. The Dependency InjectionThe Dependency Injection ContainerContainer
  • 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

  1. 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!
  2. 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.
  3. 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
  4. 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.
  5. Explain how the event system works here. Observer pattern. Allows you to create your own observers that are attached and dispatched with events.
  6. 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.
  7. Explain how param converters used.
  8. Mention that sf2 has default templates for different HTTP errors. These can be overridden.
  9. 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.
  10. Mention what flash messages are and. Explain that the session object stores the flash messages in a 'FlashBag' class.
  11. 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.
  12. 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.
  13. 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.
  14. Mention that the EventSubscriberInterface notifies the dispatcher what events it listens to. Call addSubscriber() method on the dispatcher to add a subscriber.
  15. Mention that the event object is available in the scope after being dispatched. Therefore it can hold the results of the event dispatch.
  16. Note that the name of a service is what it is referred to when you want to fetch an instance.