The Components Book (2.2)
This work is licensed under the “Attribution-Share Alike 3.0 Unported” license (http://creativecommons.org/
licenses/by-sa/3.0/).
You are free to share (to copy, distribute and transmit the work), and to remix (to adapt the work) under the
following conditions:
• Attribution: You must attribute the work in the manner specified by the author or licensor (but
not in any way that suggests that they endorse you or your use of the work).
• Share Alike: If you alter, transform, or build upon this work, you may distribute the resulting work
only under the same, similar or a compatible license. For any reuse or distribution, you must make
clear to others the license terms of this work.
The information in this book is distributed on an “as is” basis, without warranty. Although every precaution
has been taken in the preparation of this work, neither the author(s) nor SensioLabs shall have any liability to
any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by
the information contained in this work.
If you find typos or errors, feel free to report them by creating a ticket on the Symfony ticketing system
(http://github.com/symfony/symfony-docs/issues). Based on tickets and users feedback, this book is
continuously updated.

How to Install and Use the Symfony2
Components
If you're starting a new project (or already have a project) that will use one or more components, the
easiest way to integrate everything is with Composer1. Composer is smart enough to download the
component(s) that you need and take care of autoloading so that you can begin using the libraries
immediately.
This article will take you through using the The Finder Component, though this applies to using any
component.

Using the Finder Component
1. If you're creating a new project, create a new empty directory for it.
2. Create a new file called composer.json and paste the following into it:
Listing 1-1

1 {
2
3
4
5 }

"require": {
"symfony/finder": "2.2.*"
}

If you already have a composer.json file, just add this line to it. You may also need to adjust the version
(e.g. 2.1.1 or 2.2.*).
You can research the component names and versions at packagist.org2.
3. Install composer3 if you don't already have it present on your system:
4. Download the vendor libraries and generate the vendor/autoload.php file:
Listing 1-2

5. Write your code:
Once Composer has downloaded the component(s), all you need to do is include the vendor/
autoload.php file that was generated by Composer. This file takes care of autoloading all of the libraries
so that you can use them immediately:
Listing 1-3

1
2
3
4
5
6
7
8
9
10
11

// File: src/script.php
// update this to the path to the "vendor/" directory, relative to this file
require_once '../vendor/autoload.php';
use Symfony\Component\Finder\Finder;
$finder = new Finder();
$finder->in('../data/');

// ...

If you want to use all of the Symfony2 Components, then instead of adding them one by one:

This will include the Bundle and Bridge libraries, which you may not actually need.

Now What?
Now that the component is installed and autoloaded, read the specific component's documentation to
find out more about how to use it.
And have fun!

PDF brought to you by
generated on March 17, 2013

Chapter 1: How to Install and Use the Symfony2 Components | 6

Chapter 2

The ClassLoader Component
The ClassLoader Component loads your project classes automatically if they follow some
standard PHP conventions.
Whenever you use an undefined class, PHP uses the autoloading mechanism to delegate the loading of a
file defining the class. Symfony2 provides a "universal" autoloader, which is able to load classes from files
that implement one of the following conventions:
• The technical interoperability standards1 for PHP 5.3 namespaces and class names;
• The PEAR2 naming convention for classes.
If your classes and the third-party libraries you use for your project follow these standards, the Symfony2
autoloader is the only autoloader you will ever need.

Installation
You can install the component in many different ways:
• Use the official Git repository (https://github.com/symfony/ClassLoader3);
• Install it via Composer (symfony/class-loader on Packagist4).

Usage
New in version 2.1: The useIncludePath method was added in Symfony 2.1.

In this example, if you try to use a class in the Doctrine\Common namespace or one of its children, the
autoloader will first look for the class under the doctrine-common directory, and it will then fallback to
the default Doctrine directory (the last one configured) if not found, before giving up. The order of the
registrations is significant in this case.

PDF brought to you by
generated on March 17, 2013

Chapter 2: The ClassLoader Component | 9

Chapter 3

The Config Component

Introduction
The Config Component provides several classes to help you find, load, combine, autofill and validate
configuration values of any kind, whatever their source may be (Yaml, XML, INI files, or for instance a
database).

Installation
You can install the component in many different ways:
• Use the official Git repository (https://github.com/symfony/Config1);
• Install it via Composer (symfony/config on Packagist2).

The locator receives a collection of locations where it should look for files. The first argument of
locate() is the name of the file to look for. The second argument may be the current path and when
supplied, the locator will look in this directory first. The third argument indicates whether or not the
locator should return the first file it has found, or an array containing all matches.

Resource loaders
For each type of resource (Yaml, XML, annotation, etc.) a loader must be defined. Each loader should
implement LoaderInterface2 or extend the abstract FileLoader3 class, which allows for recursively
importing other resources:
Listing 4-2

Finding the right loader
The LoaderResolver4 receives as its first constructor argument a collection of loaders. When a resource
(for instance an XML file) should be loaded, it loops through this collection of loaders and returns the
loader which supports this particular resource type.
The DelegatingLoader5 makes use of the LoaderResolver6. When it is asked to load a resource, it
delegates this question to the LoaderResolver7. In case the resolver has found a suitable loader, this
loader will be asked to load the resource:
Listing 4-3

1
2
3
4
5
6
7
8
9
10
11

use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Loader\DelegatingLoader;
$loaderResolver = new LoaderResolver(array(new YamlUserLoader($locator)));
$delegatingLoader = new DelegatingLoader($loaderResolver);
$delegatingLoader->load(__DIR__.'/users.yml');
/*
The YamlUserLoader will be used to load this resource,
since it supports files with a "yml" extension
*/

Caching based on resources
When all configuration resources are loaded, you may want to process the configuration values and
combine them all in one file. This file acts like a cache. Its contents donâ&#x20AC;&#x2122;t have to be regenerated every
time the application runs â&#x20AC;&#x201C; only when the configuration resources are modified.
For example, the Symfony Routing component allows you to load all routes, and then dump a URL
matcher or a URL generator based on these routes. In this case, when one of the resources is modified
(and you are working in a development environment), the generated file should be invalidated and
regenerated. This can be accomplished by making use of the ConfigCache1 class.
The example below shows you how to collect resources, then generate some code based on the resources
that were loaded, and write this code to the cache. The cache also receives the collection of resources that
were used for generating the code. By looking at the "last modified" timestamp of these resources, the
cache can tell if it is still fresh or that its contents should be regenerated:
Listing 5-1

// the second argument indicates whether or not you want to use debug mode
$userMatcherCache = new ConfigCache($cachePath, true);
if (!$userMatcherCache->isFresh()) {
// fill this with an array of 'users.yml' file paths
$yamlUserFiles = ...;
$resources = array();
foreach ($yamlUserFiles as $yamlUserFile) {
// see the previous article "Loading resources" to
// see where $delegatingLoader comes from
$delegatingLoader->load($yamlUserFile);
$resources[] = new FileResource($yamlUserFile);
}

In debug mode, a .meta file will be created in the same directory as the cache file itself. This .meta file
contains the serialized resources, whose timestamps are used to determine if the cache is still fresh. When
not in debug mode, the cache is considered to be "fresh" as soon as it exists, and therefore no .meta file
will be generated.

PDF brought to you by
generated on March 17, 2013

Chapter 5: Caching based on resources | 14

Chapter 6

Defining and processing configuration values

Validating configuration values
After loading configuration values from all kinds of resources, the values and their structure can be
validated using the "Definition" part of the Config Component. Configuration values are usually
expected to show some kind of hierarchy. Also, values should be of a certain type, be restricted in number
or be one of a given set of values. For example, the following configuration (in Yaml) shows a clear
hierarchy and some validation rules that should be applied to it (like: "the value for auto_connect must
be a boolean value"):
Listing 6-1

When loading multiple configuration files, it should be possible to merge and overwrite some values.
Other values should not be merged and stay as they are when first encountered. Also, some keys are only
available when another key has a specific value (in the sample configuration above: the memory key only
makes sense when the driver is sqlite).

PDF brought to you by
generated on March 17, 2013

Chapter 6: Defining and processing configuration values | 15

Defining a hierarchy of configuration values using the TreeBuilder
All the rules concerning configuration values can be defined using the TreeBuilder1.
A TreeBuilder2 instance should be returned from a custom Configuration class which implements the
ConfigurationInterface3:
Listing 6-2

Adding node definitions to the tree
Variable nodes
A tree contains node definitions which can be laid out in a semantic way. This means, using indentation
and the fluent notation, it is possible to reflect the real structure of the configuration values:
Listing 6-3

The root node itself is an array node, and has children, like the boolean node auto_connect and the
scalar node default_connection. In general: after defining a node, a call to end() takes you one step up
in the hierarchy.

Node type
It is possible to validate the type of a provided value by using the appropriate node definition. Node type
are available for:
1. http://api.symfony.com/2.2/Symfony/Component/Config/Definition/Builder/TreeBuilder.html
2. http://api.symfony.com/2.2/Symfony/Component/Config/Definition/Builder/TreeBuilder.html
3. http://api.symfony.com/2.2/Symfony/Component/Config/Definition/ConfigurationInterface.html

A prototype can be used to add a definition which may be repeated many times inside the current node.
According to the prototype definition in the example above, it is possible to have multiple connection
arrays (containing a driver, host, etc.).

Array node options
Before defining the children of an array node, you can provide options like:
useAttributeAsKey()
Provide the name of a child node, whose value should be used as the key in the resulting array.
requiresAtLeastOneElement()
There should be at least one element in the array (works only when isRequired() is also called).
addDefaultsIfNotSet()
If any child nodes have default values, use them if explicit values haven't been provided.
An example of this:
Listing 6-7

In XML, each parameters node would have a name attribute (along with value), which would be
removed and used as the key for that element in the final array. The useAttributeAsKey is useful for
normalizing how arrays are specified between different formats like XML and YAML.
PDF brought to you by
generated on March 17, 2013

Chapter 6: Defining and processing configuration values | 18

Default and required values
For all node types, it is possible to define default values and replacement values in case a node has a
certain value:
defaultValue()
Set a default value
isRequired()
Must be defined (but may be empty)
cannotBeEmpty()
May not contain an empty value
default*()
(null, true, false), shortcut for defaultValue()
treat*Like()
(null, true, false), provide a replacement value in case the value is *.
Listing 6-9

The canBeDisabled method looks about the same except that the section would be enabled by default.

Merging options
Extra options concerning the merge process may be provided. For arrays:
performNoDeepMerging()
When the value is also defined in a second configuration array, donâ&#x20AC;&#x2122;t try to merge an array, but
overwrite it entirely
For all nodes:
cannotBeOverwritten()
donâ&#x20AC;&#x2122;t let other configuration arrays overwrite an existing value for this node

Appending sections
If you have a complex configuration to validate then the tree can grow to be large and you may want to
split it up into sections. You can do this by making a section a separate node and then appending it into
the main tree with append():
Listing 6-11

This is also useful to help you avoid repeating yourself if you have sections of the config that are repeated
in different places.

Normalization
When the config files are processed they are first normalized, then merged and finally the tree is used
to validate the resulting array. The normalization process is used to remove some of the differences that
result from different configuration formats, mainly the differences between Yaml and XML.
The separator used in keys is typically _ in Yaml and - in XML. For example, auto_connect in Yaml and
auto-connect. The normalization would make both of these auto_connect.
Another difference between Yaml and XML is in the way arrays of values may be represented. In Yaml
you may have:

As well as fixing this, fixXmlConfig ensures that single xml elements are still turned into an array. So
you may have:
Listing 6-16

1 <connection>default</connection>
2 <connection>extra</connection>

and sometimes only:
Listing 6-17

1 <connection>default</connection>

By default connection would be an array in the first case and a string in the second making it difficult to
validate. You can ensure it is always an array with with fixXmlConfig.
You can further control the normalization process if you need to. For example, you may want to allow a
string to be set and used as a particular key or several keys to be set explicitly. So that, if everything apart
from name is optional in this config:
Listing 6-18

Validation rules
More advanced validation rules can be provided using the ExprBuilder8. This builder implements a
fluent interface for a well-known control structure. The builder is used for adding advanced validation
rules to node definitions, like:
Listing 6-21

A validation rule also requires a "then" part:
8. http://api.symfony.com/2.2/Symfony/Component/Config/Definition/Builder/ExprBuilder.html

PDF brought to you by
generated on March 17, 2013

Chapter 6: Defining and processing configuration values | 23

•
•
•
•

then()
thenEmptyArray()
thenInvalid()
thenUnset()

Usually, "then" is a closure. Its return value will be used as a new value for the node, instead of the node's
original value.

Processing configuration values
The Processor9 uses the tree as it was built using the TreeBuilder10 to process multiple arrays of
configuration values that should be merged. If any value is not of the expected type, is mandatory and
yet undefined, or could not be validated in some other way, an exception will be thrown. Otherwise the
result is a clean array of configuration values:
Listing 6-22

The Console Component
The Console component eases the creation of beautiful and testable command line interfaces.
The Console component allows you to create command-line commands. Your console commands can be
used for any recurring task, such as cronjobs, imports, or other batch jobs.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Console1);
â&#x20AC;˘ Install it via Composer (symfony/console on Packagist2).
Windows does not support ANSI colors by default so the Console Component detects and disables
colors where Windows does not have support. However, if Windows is not configured with an
ANSI driver and your console commands invoke other scripts which emit ANSI color sequences,
they will be shown as raw escape characters.
To enable ANSI colour support for Windows, please install ANSICON3.

Creating a basic Command
To make a console command that greets you from the command line, create GreetCommand.php and add
the following to it:
Listing 7-1

Available foreground and background colors are: black, red, green, yellow, blue, magenta, cyan and
white.
And available options are: bold, underscore, blink, reverse and conceal.
You can also set these colors and options inside the tagname:
Listing 7-9

Using Command Arguments
The most interesting part of the commands are the arguments and options that you can make available.
Arguments are the strings - separated by spaces - that come after the command name itself. They are
ordered, and can be optional or required. For example, add an optional last_name argument to the
command and make the name argument required:
Listing 7-10

Using Command Options
Unlike arguments, options are not ordered (meaning you can specify them in any order) and are specified
with two dashes (e.g. --yell - you can also declare a one-letter shortcut that you can call with a single
dash like -y). Options are always optional, and can be setup to accept a value (e.g. dir=src) or simply as
a boolean flag without a value (e.g. yell).
It is also possible to make an option optionally accept a value (so that --yell or yell=loud work).
Options can also be configured to accept an array of values.

For example, add a new option to the command that can be used to specify how many times in a row the
message should be printed:
Listing 7-13

The first example will only print once, since iterations is empty and defaults to 1 (the last argument of
addOption). The second example will print five times.
Recall that options don't care about their order. So, either of the following will work:
Listing 7-16

InputOption::VALUE_REQUIRED This value is required (e.g. --iterations=5), the option itself
is still optional
InputOption::VALUE_OPTIONAL This option may or may not have a value (e.g. yell or
yell=loud)
You can combine VALUE_IS_ARRAY with VALUE_REQUIRED or VALUE_OPTIONAL like this:
Listing 7-17

Testing Commands
Symfony2 provides several tools to help you test your commands. The most useful one is the
CommandTester5 class. It uses special input and output classes to ease testing without a real console:
Listing 7-18

The getDisplay()6 method returns what would have been displayed during a normal call from the
console.
You can test sending arguments and options to the command by passing them as an array to the
execute()7 method:
Listing 7-19

You can also test a whole console application by using ApplicationTester8.

Calling an existing Command
If a command depends on another one being run before it, instead of asking the user to remember the
order of execution, you can call it directly yourself. This is also useful if you want to create a "meta"
command that just runs a bunch of other commands (for instance, all commands that need to be run
when the project's code has changed on the production servers: clearing the cache, generating Doctrine2
proxies, dumping Assetic assets, ...).
Calling a command from another one is straightforward:
Listing 7-20

First, you find()9 the command you want to execute by passing the command name.
Then, you need to create a new ArrayInput10 with the arguments and options you want to pass to the
command.
Eventually, calling the run() method actually executes the command and returns the returned code from
the command (return value from command's execute() method).
Most of the time, calling a command from code that is not executed on the command line is not
a good idea for several reasons. First, the command's output is optimized for the console. But
more important, you can think of a command as being like a controller; it should use the model to
do something and display feedback to the user. So, instead of calling a command from the Web,
refactor your code and move the logic to a new class.

Learn More!
â&#x20AC;˘ Using Console Commands, Shortcuts and Built-in Commands
â&#x20AC;˘ Building a Single Command Application

PDF brought to you by
generated on March 17, 2013

Chapter 7: The Console Component | 32

Chapter 8

Using Console Commands, Shortcuts and Builtin Commands
In addition to the options you specify for your commands, there are some built-in options as well as a
couple of built-in commands for the console component.
These examples assume you have added a file app/console to run at the cli:
Listing 8-1

You can suppress any interactive questions from the command you are running with:
Listing 8-15

1 $ php app/console list --no-interaction
2 $ php app/console list -n

Shortcut Syntax
You do not have to type out the full command names. You can just type the shortest unambiguous name
to run a command. So if there are non-clashing commands, then you can run help like this:
Listing 8-16

1 $ php app/console h

If you have commands using : to namespace commands then you just have to type the shortest
unambiguous text for each part. If you have created the demo:greet as shown in The Console Component
then you can run it with:
Listing 8-17

1 $ php app/console d:g Fabien

If you enter a short command that's ambiguous (i.e. there are more than one command that match), then
no command will be run and some suggestions of the possible commands to choose from will be output.

Building a Single Command Application
When building a command line tool, you may not need to provide several commands. In such case,
having to pass the command name each time is tedious. Fortunately, it is possible to remove this need by
extending the application:
Listing 9-1

/**
* Gets the default commands that should always be available.
*
* @return array An array of default Command instances
*/
protected function getDefaultCommands()
{
// Keep the core default commands to have the HelpCommand
// which is used when using the --help option
$defaultCommands = parent::getDefaultCommands();
$defaultCommands[] = new MyCommand();

PDF brought to you by
generated on March 17, 2013

Chapter 9: Building a Single Command Application | 36

33
34
35
36 }

return $defaultCommands;
}

When calling your console script, the command MyCommand will then always be used, without having
to pass its name.

PDF brought to you by
generated on March 17, 2013

Chapter 9: Building a Single Command Application | 37

Chapter 10

Dialog Helper
The DialogHelper1 provides functions to ask the user for more information. It is included in the default
helper set, which you can get by calling getHelperSet()2:
Listing 10-1

1 $dialog = $this->getHelperSet()->get('dialog');

All the methods inside the Dialog Helper have an OutputInterface3 as first the argument, the question
as the second argument and the default value as last argument.

Asking the User for confirmation
Suppose you want to confirm an action before actually executing it. Add the following to your command:
Listing 10-2

In this case, the user will be asked "Continue with this action", and will return true if the user answers
with y or false in any other case. The third argument to askConfirmation is the default value to return if
the user doesn't enter any input.

The user will be asked "Please enter the name of the bundle". She can type some name which will be
returned by the ask method. If she leaves it empty, the default value (AcmeDemoBundle here) is returned.

Hiding the User's Response
New in version 2.2: The askHiddenResponse method was added in Symfony 2.2.

You can also ask a question and hide the response. This is particularly convenient for passwords:
Listing 10-4

When you ask for a hidden response, Symfony will use either a binary, change stty mode or use
another trick to hide the response. If none is available, it will fallback and allow the response to
be visible unless you pass false as the third argument like in the example above. In this case, a
RuntimeException would be thrown.

Validating the Answer
You can even validate the answer. For instance, in the last example you asked for the bundle name.
Following the Symfony2 naming conventions, it should be suffixed with Bundle. You can validate that
by using the askAndValidate()4 method:
Listing 10-5

The $validator is a callback which handles the validation. It should throw an exception if there is
something wrong. The exception message is displayed in the console, so it is a good practice to put some
useful information in it. The callback function should also return the value of the user's input if the
validation was successful.
You can set the max number of times to ask in the $attempts argument. If you reach this max number it
will use the default value, which is given in the last argument. Using false means the amount of attempts
is infinite. The user will be asked as long as he provides an invalid answer and will only be able to proceed
if her input is valid.

Hiding the User's Response
New in version 2.2: The askHiddenResponseAndValidate method was added in Symfony 2.2.

If you want to allow the response to be visible if it cannot be hidden for some reason, pass true as the
fifth argument.

PDF brought to you by
generated on March 17, 2013

Chapter 10: Dialog Helper | 40

Let the user choose from a list of Answers
New in version 2.2: The select()5 method was added in Symfony 2.2.

If you have a predefined set of answers the user can choose from, you could use the ask method described
above or, to make sure the user provided a correct answer, the askAndValidate method. Both have the
disadvantage that you need to handle incorrect values yourself.
Instead, you can use the select()6 method, which makes sure that the user can only enter a valid string
from a predefined list:
Listing 10-8

The option which should be selected by default is provided with the fourth parameter. The default is
null, which means that no option is the default one.
If the user enters an invalid string, an error message is shown and the user is asked to provide the answer
another time, until she enters a valid string or the maximum attempts is reached (which you can define
in the fifth parameter). The default value for the attempts is false, which means infinite attempts. You
can define your own error message in the sixth parameter.

Formatter Helper
The Formatter helpers provides functions to format the output with colors. You can do more advanced
things with this helper than you can in Coloring the Output.
The FormatterHelper1 is included in the default helper set, which you can get by calling
getHelperSet()2:
Listing 11-1

1 $formatter = $this->getHelperSet()->get('formatter');

The methods return a string, which you'll usually render to the console by passing it to the
OutputInterface::writeln3 method.

Print Messages in a Section
Symfony offers a defined style when printing a message that belongs to some "section". It prints the
section in color and with brackets around it and the actual message to the right of this. Minus the color,
it looks like this:
Listing 11-2

1 [SomeSection] Here is some message related to that section

To reproduce this style, you can use the formatSection()4 method:
Listing 11-3

Print Messages in a Block
Sometimes you want to be able to print a whole block of text with a background color. Symfony uses this
when printing error messages.
If you print your error message on more than one line manually, you will notice that the background is
only as long as each individual line. Use the formatBlock()5 to generate a block output:
Listing 11-4

As you can see, passing an array of messages to the formatBlock()6 method creates the desired output.
If you pass true as third parameter, the block will be formatted with more padding (one blank line above
and below the messages and 2 spaces on the left and right).
The exact "style" you use in the block is up to you. In this case, you're using the pre-defined error style,
but there are other styles, or you can create your own. See Coloring the Output.

When executing longer-running commands, it may be helpful to show progress information, which
updates as your command runs:
../../../_images/progress.png
To display progress details, use the ProgressHelper1, pass it a total number of units, and advance the
progress as your command executes:
Listing 12-1

The appearance of the progress output can be customized as well, with a number of different levels of
verbosity. Each of these displays different possible items - like percentage completion, a moving progress
bar, or current/total information (e.g. 10/50):
Listing 12-2

You can also control the different characters and the width used for the progress bar:
Listing 12-3

1
2
3
4
5
6

// the finished part of the bar
$progress->setBarCharacter('<comment>=</comment>');
// the unfinished part of the bar
$progress->setEmptyBarCharacter(' ');
$progress->setProgressCharacter('|');
$progress->setBarWidth(50);

To see other available options, check the API documentation for ProgressHelper2.
For performance reasons, be careful to not set the total number of steps to a high number. For
example, if you're iterating over a large number of items, consider a smaller "step" number that
updates on only some iterations:
Listing 12-4

Installation
You can install the component in several different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/CssSelector1);
â&#x20AC;˘ Install it via Composer (symfony/css-selector on Packagist2).

Usage
Why use CSS selectors?
When you're parsing an HTML or an XML document, by far the most powerful method is XPath.
XPath expressions are incredibly flexible, so there is almost always an XPath expression that will find
the element you need. Unfortunately, they can also become very complicated, and the learning curve is
steep. Even common operations (such as finding an element with a particular class) can require long and
unwieldy expressions.
Many developers -- particularly web developers -- are more comfortable using CSS selectors to find
elements. As well as working in stylesheets, CSS selectors are used in Javascript with the
querySelectorAll function and in popular Javascript libraries such as jQuery, Prototype and MooTools.
CSS selectors are less powerful than XPath, but far easier to write, read and understand. Since they are
less powerful, almost all CSS selectors can be converted to an XPath equivalent. This XPath expression
can then be used with other functions and classes that use XPath to find elements in a document.

You can use this expression with, for instance, DOMXPath3 or SimpleXMLElement4 to find elements in a
document.
The Crawler::filter()5 method uses the CssSelector component to find elements based on a
CSS selector string. See the The DomCrawler Component for more details.

Limitations of the CssSelector component
Not all CSS selectors can be converted to XPath equivalents.
There are several CSS selectors that only make sense in the context of a web-browser.
• link-state selectors: :link, :visited, :target
• selectors based on user action: :hover, :focus, :active
• UI-state selectors: :enabled, :disabled, :indeterminate (however, :checked and
:unchecked are available)
Pseudo-elements (:before, :after, :first-line, :first-letter) are not supported because they
select portions of text rather than elements.
Several pseudo-classes are not yet supported:
• :lang(language)
• root
• *:first-of-type, *:last-of-type, *:nth-of-type, *:nth-last-of-type, *:only-oftype. (These work with an element name (e.g. li:first-of-type) but not with *.

While possible, the DomCrawler component is not designed for manipulation of the DOM or redumping HTML/XML.

Installation
You can install the component in many different ways:
• Use the official Git repository (https://github.com/symfony/DomCrawler1);
• Install it via Composer (symfony/dom-crawler on Packagist2).

Usage
The Crawler3 class provides methods to query and manipulate HTML and XML documents.
An instance of the Crawler represents a set (SplObjectStorage4) of DOMElement5 objects, which are
basically nodes that you can traverse easily:
Listing 14-1

Manipulating and Dumping a Crawler
These methods on the Crawler are intended to initially populate your Crawler and aren't intended
to be used to further manipulate a DOM (though this is possible). However, since the Crawler
is a set of DOMElement13 objects, you can use any method or property available on DOMElement14,
DOMNode15 or DOMDocument16. For example, you could get the HTML of a Crawler with something
like this:
Listing 14-16

Form and Link support
Special treatment is given to links and forms inside the DOM tree.

Links
To find a link by name (or a clickable image by its alt attribute), use the selectLink method on an
existing crawler. This returns a Crawler instance with just the selected link(s). Calling link() gives you
a special Link17 object:
Listing 14-17

// or do this all at once
$link = $crawler->selectLink('Go elsewhere...')->link();

The Link18 object has several useful methods to get more information about the selected link itself:
Listing 14-18

1 // return the proper URI that can be used to make another request
2 $uri = $link->getUri();

The getUri() is especially useful as it cleans the href value and transforms it into how it should
really be processed. For example, for a link with href="#foo", this would return the full URI of
the current page suffixed with #foo. The return from getUri() is always a full URI that you can
act on.

Forms
Special treatment is also given to forms. A selectButton() method is available on the Crawler which
returns another Crawler that matches a button (input[type=submit], input[type=image], or a button)
with the given text. This method is especially useful because you can use it to return a Form19 object that
represents the form that the button lives in:
Listing 14-19

The getUri()21 method does more than just return the action attribute of the form. If the form method
is GET, then it mimics the browser's behavior and returns the action attribute followed by a query string
of all of the form's values.
You can virtually set and get values on the form:
Listing 14-21

1
2
3
4
5
6
7
8
9
10
11
12

// set values on the form internally
$form->setValues(array(
'registration[username]' => 'symfonyfan',
'registration[terms]'
=> 1,
));
// get back an array of values - in the "flat" array like above
$values = $form->getValues();
// returns the values like PHP would see them,
// where "registration" is its own array
$values = $form->getPhpValues();

One great example of an integrated system that uses all of this is Goutte22. Goutte understands the
Symfony Crawler object and can use it to submit forms directly:
Listing 14-27

1
2
3
4
5
6
7
8
9
10
11
12
13

use Goutte\Client;

// make a real request to an external site
$client = new Client();
$crawler = $client->request('GET', 'https://github.com/login');
// select the form and fill in some values
$form = $crawler->selectButton('Log in')->form();
$form['login'] = 'symfonyfan';
$form['password'] = 'anypass';
// submit that form
$crawler = $client->submit($form);

22. https://github.com/fabpot/goutte

PDF brought to you by
generated on March 17, 2013

Chapter 14: The DomCrawler Component | 54

Chapter 15

The Dependency Injection Component
The Dependency Injection component allows you to standardize and centralize the way objects
are constructed in your application.
For an introduction to Dependency Injection and service containers see Service Container

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/DependencyInjection1);
â&#x20AC;˘ Install it via Composer (symfony/dependency-injection on Packagist2).

Basic Usage
You might have a simple class like the following Mailer that you want to make available as a service:
Listing 15-1

This class is now much more flexible as you have separated the choice of transport out of the
implementation and into the container.
Which mail transport you have chosen may be something other services need to know about. You can
avoid having to change it in multiple places by making it a parameter in the container and then referring
to this parameter for the Mailer service's constructor argument:
Listing 15-5

Avoiding Your Code Becoming Dependent on the Container
Whilst you can retrieve services from the container directly it is best to minimize this. For example, in the
NewsletterManager you injected the mailer service in rather than asking for it from the container. You
could have injected the container in and retrieved the mailer service from it but it would then be tied to
this particular container making it difficult to reuse the class elsewhere.
You will need to get a service from the container at some point but this should be as few times as possible
at the entry point to your application.

Setting Up the Container with Configuration Files
As well as setting up the services using PHP as above you can also use configuration files. To do this you
also need to install the Config Component.
Loading an XML config file:
Listing 15-11

1
2
3
4
5
6
7

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
$container = new ContainerBuilder();
$loader = new XmlFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.xml');

Loading a YAML config file:
Listing 15-12

1
2
3
4
5
6
7

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.yml');

If you want to load YAML config files then you will also need to install The YAML component.

The newsletter_manager and mailer services can be set up using config files:
Listing 15-13

Types of Injection
Making a class's dependencies explicit and requiring that they be injected into it is a good way of making
a class more reusable, testable and decoupled from others.
There are several ways that the dependencies can be injected. Each injection point has advantages
and disadvantages to consider, as well as different ways of working with them when using the service
container.

Constructor Injection
The most common way to inject dependencies is via a class's constructor. To do this you need to add an
argument to the constructor signature to accept the dependency:
Listing 16-1

Type hinting the injected object means that you can be sure that a suitable dependency has
been injected. By type-hinting, you'll get a clear error immediately if an unsuitable dependency
is injected. By type hinting using an interface rather than a class you can make the choice of
dependency more flexible. And assuming you only use methods defined in the interface, you can
gain that flexibility and still safely use the object.

There are several advantages to using constructor injection:
• If the dependency is a requirement and the class cannot work without it then injecting it via
the constructor ensures it is present when the class is used as the class cannot be constructed
without it.
• The constructor is only ever called once when the object is created, so you can be sure that the
dependency will not change during the object's lifetime.
These advantages do mean that constructor injection is not suitable for working with optional
dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses
constructor injection then extending it and overriding the constructor becomes problematic.

Setter Injection
Another possible injection point into a class is by adding a setter method that accepts the dependency:
Listing 16-3

This time the advantages are:
• Setter injection works well with optional dependencies. If you do not need the dependency,
then just do not call the setter.
• You can call the setter multiple times. This is particularly useful if the method adds the
dependency to a collection. You can then have a variable number of dependencies.
The disadvantages of setter injection are:
• The setter can be called more than just at the time of construction so you cannot be sure the
dependency is not replaced during the lifetime of the object (except by explicitly writing the
setter method to check if has already been called).

PDF brought to you by
generated on March 17, 2013

Chapter 16: Types of Injection | 61

â&#x20AC;˘ You cannot be sure the setter will be called and so you need to add checks that any required
dependencies are injected.

Property Injection
Another possibility is just setting public fields of the class directly:
Listing 16-5

There are mainly only disadvantages to using property injection, it is similar to setter injection but with
these additional important problems:
â&#x20AC;˘ You cannot control when the dependency is set at all, it can be changed at any point in the
object's lifetime.
â&#x20AC;˘ You cannot use type hinting so you cannot be sure what dependency is injected except by
writing into the class code to explicitly test the class instance before using it.
But, it is useful to know that this can be done with the service container, especially if you are working
with code that is out of your control, such as in a third party library, which uses public properties for its
dependencies.

PDF brought to you by
generated on March 17, 2013

Chapter 16: Types of Injection | 62

Chapter 17

Working with Container Parameters and
Definitions

Getting and Setting Container Parameters
Working with container parameters is straight forward using the container's accessor methods for
parameters. You can check if a parameter has been defined in the container with:
Listing 17-1

1 $container->hasParameter($name);

You can retrieve parameters set in the container with:
Listing 17-2

1 $container->getParameter($name);

and set a parameter in the container with:
Listing 17-3

1 $container->setParameter($name, $value);

Getting and Setting Service Definitions
There are also some helpful methods for working with the service definitions.
To find out if there is a definition for a service id:
Listing 17-4

1 $container->hasDefinition($serviceId);

This is useful if you only want to do something if a particular definition exists.
You can retrieve a definition with:

PDF brought to you by
generated on March 17, 2013

Chapter 17: Working with Container Parameters and Definitions | 63

Listing 17-5

1 $container->getDefinition($serviceId);

or:
Listing 17-6

1 $container->findDefinition($serviceId);

which unlike getDefinition() also resolves aliases so if the $serviceId argument is an alias you will
get the underlying definition.
The service definitions themselves are objects so if you retrieve a definition with these methods and make
changes to it these will be reflected in the container. If, however, you are creating a new definition then
you can add it to the container using:
Listing 17-7

1 $container->setDefinition($id, $definition);

Working with a definition
Creating a new definition
If you need to create a new definition rather than manipulate one retrieved from then container then the
definition class is Definition1.

Class
First up is the class of a definition, this is the class of the object returned when the service is requested
from the container.
To find out what class is set for a definition:
Listing 17-8

In a similar way you can replace an already set argument by index using:
Listing 17-14

1 $definition->replaceArgument($index, $argument);

You can also replace all the arguments (or set some if there are none) with an array of arguments:
Listing 17-15

1 $definition->replaceArguments($arguments);

Method Calls
If the service you are working with uses setter injection then you can manipulate any method calls in the
definitions as well.
You can get an array of all the method calls with:
Listing 17-16

1 $definition->getMethodCalls();

Add a method call with:
Listing 17-17

1 $definition->addMethodCall($method, $arguments);

Where $method is the method name and $arguments is an array of the arguments to call the method with.
The arguments can be strings, arrays, parameters or service ids as with the constructor arguments.
You can also replace any existing method calls with an array of new ones with:
Listing 17-18

1 $definition->setMethodCalls($methodCalls);

There are more examples of specific ways of working with definitions in the PHP code blocks of the
configuration examples on pages such as Using a Factory to Create Services and Managing Common
Dependencies with Parent Services.

PDF brought to you by
generated on March 17, 2013

Chapter 17: Working with Container Parameters and Definitions | 65

Chapter 18

Compiling the Container
The service container can be compiled for various reasons. These reasons include checking for any
potential issues such as circular references and making the container more efficient by resolving
parameters and removing unused services.
It is compiled by running:
Listing 18-1

1 $container->compile();

The compile method uses Compiler Passes for the compilation. The Dependency Injection component
comes with several passes which are automatically registered for compilation. For example the
CheckDefinitionValidityPass1 checks for various potential issues with the definitions that have been
set in the container. After this and several other passes that check the container's validity, further
compiler passes are used to optimize the configuration before it is cached. For example, private services
and abstract services are removed, and aliases are resolved.

Managing Configuration with Extensions
As well as loading configuration directly into the container as shown in The Dependency Injection
Component, you can manage it by registering extensions with the container. The first step in the
compilation process is to load configuration from any extension classes registered with the container.
Unlike the configuration loaded directly, they are only processed when the container is compiled. If
your application is modular then extensions allow each module to register and manage their own service
configuration.
The extensions must implement ExtensionInterface2 and can be registered with the container with:
Listing 18-2

1 $container->registerExtension($extension);

The main work of the extension is done in the load method. In the load method you can load
configuration from one or more configuration files as well as manipulate the container definitions using
the methods shown in Working with Container Parameters and Definitions.
1. http://api.symfony.com/2.2/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.html
2. http://api.symfony.com/2.2/Symfony/Component/DependencyInjection/Extension/ExtensionInterface.html

PDF brought to you by
generated on March 17, 2013

Chapter 18: Compiling the Container | 66

The load method is passed a fresh container to set up, which is then merged afterwards into the
container it is registered with. This allows you to have several extensions managing container definitions
independently. The extensions do not add to the containers configuration when they are added but are
processed when the container's compile method is called.
A very simple extension may just load configuration files into the container:
Listing 18-3

This does not gain very much compared to loading the file directly into the overall container being
built. It just allows the files to be split up amongst the modules/bundles. Being able to affect the
configuration of a module from configuration files outside of the module/bundle is needed to make a
complex application configurable. This can be done by specifying sections of config files loaded directly
into the container as being for a particular extension. These sections on the config will not be processed
directly by the container but by the relevant Extension.
The Extension must specify a getAlias method to implement the interface:
Listing 18-4

The $configs argument is an array containing each different config file that was loaded into the
container. You are only loading a single config file in the above example but it will still be within an array.
The array will look like this:
Listing 18-8

Whilst you can manually manage merging the different files, it is much better to use the Config
Component to merge and validate the config values. Using the configuration processing you could access
the config value this way:
Listing 18-9

There are a further two methods you must implement. One to return the XML namespace so that the
relevant parts of an XML config file are passed to the extension. The other to specify the base path to
XSD files to validate the XML configuration:
Listing 18-10

In the Symfony2 full stack framework there is a base Extension class which implements these
methods as well as a shortcut method for processing the configuration. See How to expose a
Semantic Configuration for a Bundle for more details.

The processed config value can now be added as container parameters as if it were listed in a parameters
section of the config file but with the additional benefit of merging multiple files and validation of the
configuration:
Listing 18-12

More complex configuration requirements can be catered for in the Extension classes. For example, you
may choose to load a main service configuration file but also load a secondary one only if a certain
parameter is set:
Listing 18-13

Just registering an extension with the container is not enough to get it included in the processed
extensions when the container is compiled. Loading config which uses the extension's alias as a
key as in the above examples will ensure it is loaded. The container builder can also be told to load
it with its loadFromExtension()3 method:
Listing 18-14

If you need to manipulate the configuration loaded by an extension then you cannot do it from
another extension as it uses a fresh container. You should instead use a compiler pass which works
with the full container after the extensions have been processed.

Prepending Configuration passed to the Extension
New in version 2.2: The ability to prepend the configuration of a bundle is new in Symfony 2.2.

For more details, see How to simplify configuration of multiple Bundles, which is specific to the Symfony2
Framework, but contains more details about this feature.

Creating a Compiler Pass
You can also create and register your own compiler passes with the container. To create a compiler pass it
needs to implement the CompilerPassInterface5 interface. The compiler pass gives you an opportunity
to manipulate the service definitions that have been compiled. This can be very powerful, but is not
something needed in everyday use.
The compiler pass must have the process method which is passed the container being compiled:
Listing 18-16

The container's parameters and definitions can be manipulated using the methods described in the
Working with Container Parameters and Definitions. One common thing to do in a compiler pass is to
search for all services that have a certain tag in order to process them in some way or dynamically plug
each into some other service.

Registering a Compiler Pass
You need to register your custom pass with the container. Its process method will then be called when
the container is compiled:
Listing 18-17

Compiler passes are registered differently if you are using the full stack framework, see How to
work with Compiler Passes in Bundles for more details.

Controlling the Pass Ordering
The default compiler passes are grouped into optimization passes and removal passes. The optimization
passes run first and include tasks such as resolving references within the definitions. The removal passes
perform tasks such as removing private aliases and unused services. You can choose where in the order
any custom passes you add are run. By default they will be run before the optimization passes.
You can use the following constants as the second argument when registering a pass with the container
to control where it goes in the order:
•
•
•
•
•

For example, to run your custom pass after the default removal passes have been run:
Listing 18-18

1
2
3
4
5
6
7
8

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
$container = new ContainerBuilder();
$container->addCompilerPass(
new CustomCompilerPass,
PassConfig::TYPE_AFTER_REMOVING
);

Dumping the Configuration for Performance
Using configuration files to manage the service container can be much easier to understand than using
PHP once there are a lot of services. This ease comes at a price though when it comes to performance as
the config files need to be parsed and the PHP configuration built from them. The compilation process
makes the container more efficient but it takes time to run. You can have the best of both worlds though
by using configuration files and then dumping and caching the resulting configuration. The PhpDumper
makes dumping the compiled container easy:
Listing 18-19

You will now get the speed of the PHP configured container with the ease of using configuration files.
Additionally dumping the container in this way further optimizes how the services are created by the
container.
In the above example you will need to delete the cached container file whenever you make any changes.
Adding a check for a variable that determines if you are in debug mode allows you to keep the speed
of the cached container in production but getting an up to date configuration whilst developing your
application:
Listing 18-21

This could be further improved by only recompiling the container in debug mode when changes have
been made to its configuration rather than on every request. This can be done by caching the resource
files used to configure the container in the way described in "Caching based on resources" in the config
component documentation.
You do not need to work out which files to cache as the container builder keeps track of all the resources
used to configure it, not just the configuration files but the extension classes and compiler passes as well.
This means that any changes to any of these files will invalidate the cache and trigger the container being
rebuilt. You just need to ask the container for these resources and use them as metadata for the cache:
Listing 18-22

Now the cached dumped container is used regardless of whether debug mode is on or not. The difference
is that the ConfigCache is set to debug mode with its second constructor argument. When the cache is
not in debug mode the cached container will always be used if it exists. In debug mode, an additional
metadata file is written with the timestamps of all the resource files. These are then checked to see if the
files have changed, if they have the cache will be considered stale.
In the full stack framework the compilation and caching of the container is taken care of for you.

PDF brought to you by
generated on March 17, 2013

Chapter 18: Compiling the Container | 74

Chapter 19

Working with Tagged Services
Tags are a generic string (along with some options) that can be applied to any service. By themselves,
tags don't actually alter the functionality of your services in any way. But if you choose to, you can ask a
container builder for a list of all services that were tagged with some specific tag. This is useful in compiler
passes where you can find these services and use or modify them in some specific way.
For example, if you are using Swift Mailer you might imagine that you want to implement a "transport
chain", which is a collection of classes implementing \Swift_Transport. Using the chain, you'll want
Swift Mailer to try several ways of transporting the message until one succeeds.
To begin with, define the TransportChain class:
Listing 19-1

Define Services with a Custom Tag
Now you might want several of the \Swift_Transport classes to be instantiated and added to the chain
automatically using the addTransport() method. For example you may add the following transports as
services:
Listing 19-3

The process() method checks for the existence of the acme_mailer.transport_chain service, then
looks for all services tagged acme_mailer.transport. It adds to the definition of the
acme_mailer.transport_chain service a call to addTransport() for each "acme_mailer.transport"
service it has found. The first argument of each of these calls will be the mailer transport service itself.
PDF brought to you by
generated on March 17, 2013

Chapter 19: Working with Tagged Services | 76

Register the Pass with the Container
You also need to register the pass with the container, it will then be run when the container is compiled:
Listing 19-5

Compiler passes are registered differently if you are using the full stack framework. See How to
work with Compiler Passes in Bundles for more details.

Adding additional attributes on Tags
Sometimes you need additional information about each service that's tagged with your tag. For example,
you might want to add an alias to each TransportChain.
To begin with, change the TransportChain class:
Listing 19-6

As you can see, when addTransport is called, it takes not only a Swift_Transport object, but also a
string alias for that transport. So, how can you allow each tagged transport service to also supply an alias?
To answer this, change the service declaration:
Listing 19-7

The trickiest part is the $attributes variable. Because you can use the same tag many times on the same
service (e.g. you could theoretically tag the same service 5 times with the acme_mailer.transport tag),
$attributes is an array of the tag information for each tag on that service.

PDF brought to you by
generated on March 17, 2013

Chapter 19: Working with Tagged Services | 78

Chapter 20

Using a Factory to Create Services
Symfony2's Service Container provides a powerful way of controlling the creation of objects, allowing
you to specify arguments passed to the constructor as well as calling methods and setting parameters.
Sometimes, however, this will not provide you with everything you need to construct your objects. For
this situation, you can use a factory to create the object and tell the service container to call a method on
the factory rather than directly instantiating the object.
Suppose you have a factory that configures and returns a new NewsletterManager object:
Listing 20-1

When you specify the class to use for the factory (via factory_class) the method will be called statically.
If the factory itself should be instantiated and the resulting object's method called (as in this example),
configure the factory itself as a service:
PDF brought to you by
generated on March 17, 2013

The factory service is specified by its id name and not a reference to the service itself. So, you do
not need to use the @ syntax.

Passing Arguments to the Factory Method
If you need to pass arguments to the factory method, you can use the arguments options inside the
service container. For example, suppose the get method in the previous example takes the templating
service as an argument:
Listing 20-4

Configuring Services with a Service
Configurator
The Service Configurator is a feature of the Dependency Injection Container that allows you to use a
callable to configure a service after its instantiation.
You can specify a method in another service, a PHP function or a static method in a class. The service
instance is passed to the callable, allowing the configurator to do whatever it needs to configure the
service after its creation.
A Service Configurator can be used, for example, when you a have a service that requires complex setup
based on configuration settings coming from different sources/services. Using an external configurator,
you can maintain the service implementation cleanly and keep it decoupled from the other objects that
provide the configuration needed.
Another interesting use case is when you have multiple objects that share a common configuration or
that should be configured in a similar way at runtime.
For example, suppose you have an application where you send different types of emails to users. Emails
are passed through different formatters that could be enabled or not depending on some dynamic
application settings. You start defining a NewsletterManager class like this:
Listing 21-1

As mentioned before, the goal is to set the formatters at runtime depending on application settings. To
do this, you also have an EmailFormatterManager class which is responsible for loading and validating
formatters enabled in the application:
Listing 21-3

If your goal is to avoid having to couple NewsletterManager and GreetingCardManager with
EmailFormatterManager, then you might want to create a configurator class to configure these instances:
Listing 21-4

The EmailConfigurator's job is to inject the enabled filters into NewsletterManager and
GreetingCardManager because they are not aware of where the enabled filters come from. In the other
hand, the EmailFormatterManager holds the knowledge about the enabled formatters and how to load
them, keeping the single responsibility principle.

Configurator Service Config
The service config for the above classes would look something like this:
Listing 21-5

Managing Common Dependencies with Parent
Services
As you add more functionality to your application, you may well start to have related classes that share
some of the same dependencies. For example you may have a Newsletter Manager which uses setter
injection to set its dependencies:
Listing 22-1

There is a lot of repetition in both the classes and the configuration. This means that if you changed, for
example, the Mailer of EmailFormatter classes to be injected via the constructor, you would need to
update the config in two places. Likewise if you needed to make changes to the setter methods you would
need to do this in both classes. The typical way to deal with the common methods of these related classes
would be to extract them to a super class:
Listing 22-4

In this context, having a parent service implies that the arguments and method calls of the parent service
should be used for the child services. Specifically, the setter methods defined for the parent service will
be called when the child services are instantiated.
If you remove the parent config key, the services will still be instantiated and they will still of
course extend the MailManager class. The difference is that omitting the parent config key will
mean that the calls defined on the mail_manager service will not be executed when the child
services are instantiated.

The parent class is abstract as it should not be directly instantiated. Setting it to abstract in the config file
as has been done above will mean that it can only be used as a parent service and cannot be used directly
as a service to inject and will be removed at compile time. In other words, it exists merely as a "template"
that other services can use.

PDF brought to you by
generated on March 17, 2013

Chapter 22: Managing Common Dependencies with Parent Services | 86

In order for parent dependencies to resolve, the ContainerBuilder must first be compiled. See
Compiling the Container for more details.

Overriding Parent Dependencies
There may be times where you want to override what class is passed in for a dependency of one child
service only. Fortunately, by adding the method call config for the child service, the dependencies set
by the parent class will be overridden. So if you needed to pass a different dependency just to the
NewsletterManager class, the config would look like this:
Listing 22-8

The GreetingCardManager will receive the same dependencies as before, but the NewsletterManager
will be passed the my_alternative_mailer instead of the my_mailer service.

Collections of Dependencies
It should be noted that the overridden setter method in the previous example is actually called twice once per the parent definition and once per the child definition. In the previous example, that was fine,
since the second setMailer call replaces mailer object set by the first call.
In some cases, however, this can be a problem. For example, if the overridden method call involves
adding something to a collection, then two objects will be added to that collection. The following shows
such a case, if the parent class looks like this:
Listing 22-9

In this example, the setFilter of the newsletter_manager service will be called twice, resulting in the
$filters array containing both my_filter and another_filter objects. This is great if you just want to
add additional filters to the subclasses. If you want to replace the filters passed to the subclass, removing
the parent setting from the config will prevent the base class from calling setFilter.

PDF brought to you by
generated on March 17, 2013

Chapter 22: Managing Common Dependencies with Parent Services | 88

Chapter 23

Advanced Container Configuration

Marking Services as public / private
When defining services, you'll usually want to be able to access these definitions within your application
code. These services are called public. For example, the doctrine service registered with the container
when using the DoctrineBundle is a public service as you can access it via:
Listing 23-1

1 $doctrine = $container->get('doctrine');

However, there are use-cases when you don't want a service to be public. This is common when a service
is only defined because it could be used as an argument for another service.
If you use a private service as an argument to only one other service, this will result in an inlined
instantiation (e.g. new PrivateFooBar()) inside this other service, making it publicly unavailable
at runtime.

Simply said: A service will be private when you do not want to access it directly from your code.
Here is an example:
Listing 23-2

1 services:
2
foo:
3
class: Example\Foo
4
public: false

Now that the service is private, you cannot call:
Listing 23-3

1 $container->get('foo');

However, if a service has been marked as private, you can still alias it (see below) to access this service
(via the alias).

PDF brought to you by
generated on March 17, 2013

Chapter 23: Advanced Container Configuration | 89

Services are by default public.

Aliasing
You may sometimes want to use shortcuts to access some services. You can do so by aliasing them and,
furthermore, you can even alias non-public services.
Listing 23-4

1 services:
2
foo:
3
class: Example\Foo
4
bar:
5
alias: foo

This means that when using the container directly, you can access the foo service by asking for the bar
service like this:
Listing 23-5

1 $container->get('bar'); // Would return the foo service

Requiring files
There might be use cases when you need to include another file just before the service itself gets loaded.
To do so, you can use the file directive.
Listing 23-6

Notice that Symfony will internally call the PHP function require_once which means that your file will
be included only once per request.

PDF brought to you by
generated on March 17, 2013

Chapter 23: Advanced Container Configuration | 90

Chapter 24

Container Building Workflow
In the preceding pages of this section, there has been little to say about where the various files and classes
should be located. This is because this depends on the application, library or framework in which you
want to use the container. Looking at how the container is configured and built in the Symfony2 full stack
framework will help you see how this all fits together, whether you are using the full stack framework or
looking to use the service container in another application.
The full stack framework uses the HttpKernel component to manage the loading of the service container
configuration from the application and bundles and also handles the compilation and caching. Even if
you are not using HttpKernel, it should give you an idea of one way of organizing configuration in a
modular application.

Working with cached Container
Before building it, the kernel checks to see if a cached version of the container exists. The HttpKernel has
a debug setting and if this is false, the cached version is used if it exists. If debug is true then the kernel
checks to see if configuration is fresh and if it is, the cached version of the container is used. If not then the
container is built from the application-level configuration and the bundles's extension configuration.
Read Dumping the Configuration for Performance for more details.

Application-level Configuration
Application level config is loaded from the app/config directory. Multiple files are loaded which are
then merged when the extensions are processed. This allows for different configuration for different
environments e.g. dev, prod.
These files contain parameters and services that are loaded directly into the container as per Setting Up
the Container with Configuration Files. They also contain configuration that is processed by extensions as
per Managing Configuration with Extensions. These are considered to be bundle configuration since each
bundle contains an Extension class.

PDF brought to you by
generated on March 17, 2013

Chapter 24: Container Building Workflow | 91

Bundle-level Configuration with Extensions
By convention, each bundle contains an Extension class which is in the bundle's DependencyInjection
directory. These are registered with the ContainerBuilder when the kernel is booted. When the
ContainerBuilder is compiled, the application-level configuration relevant to the bundle's extension
is passed to the Extension which also usually loads its own config file(s), typically from the bundle's
Resources/config directory. The application-level config is usually processed with a Configuration
object also stored in the bundle's DependencyInjection directory.

Compiler passes to allow Interaction between Bundles
Compiler passes are used to allow interaction between different bundles as they cannot affect each
other's configuration in the extension classes. One of the main uses is to process tagged services,
allowing bundles to register services to picked up by other bundles, such as Monolog loggers, Twig
extensions and Data Collectors for the Web Profiler. Compiler passes are usually placed in the bundle's
DependencyInjection/Compiler directory.

Compilation and Caching
After the compilation process has loaded the services from the configuration, extensions and the compiler
passes, it is dumped so that the cache can be used next time. The dumped version is then used during
subsequent requests as it is more efficient.

PDF brought to you by
generated on March 17, 2013

Chapter 24: Container Building Workflow | 92

Chapter 25

The Event Dispatcher Component

Introduction
Objected Oriented code has gone a long way to ensuring code extensibility. By creating classes that have
well defined responsibilities, your code becomes more flexible and a developer can extend them with
subclasses to modify their behaviors. But if he wants to share his changes with other developers who have
also made their own subclasses, code inheritance is no longer the answer.
Consider the real-world example where you want to provide a plugin system for your project. A plugin
should be able to add methods, or do something before or after a method is executed, without interfering
with other plugins. This is not an easy problem to solve with single inheritance, and multiple inheritance
(were it possible with PHP) has its own drawbacks.
The Symfony2 Event Dispatcher component implements the Observer1 pattern in a simple and effective
way to make all these things possible and to make your projects truly extensible.
Take a simple example from the The HttpKernel Component. Once a Response object has been created, it
may be useful to allow other elements in the system to modify it (e.g. add some cache headers) before it's
actually used. To make this possible, the Symfony2 kernel throws an event - kernel.response. Here's
how it works:
• A listener (PHP object) tells a central dispatcher object that it wants to listen to the
kernel.response event;
• At some point, the Symfony2 kernel tells the dispatcher object to dispatch the
kernel.response event, passing with it an Event object that has access to the Response
object;
• The dispatcher notifies (i.e. calls a method on) all listeners of the kernel.response event,
allowing each of them to make modifications to the Response object.

Installation
You can install the component in many different ways:
1. http://en.wikipedia.org/wiki/Observer_pattern

PDF brought to you by
generated on March 17, 2013

Chapter 25: The Event Dispatcher Component | 93

• Use the official Git repository (https://github.com/symfony/EventDispatcher2);
• Install it via Composer (symfony/event-dispatcher on Packagist3).

Usage
Events
When an event is dispatched, it's identified by a unique name (e.g. kernel.response), which any
number of listeners might be listening to. An Event4 instance is also created and passed to all of the
listeners. As you'll see later, the Event object itself often contains data about the event being dispatched.

Naming Conventions
The unique event name can be any string, but optionally follows a few simple naming conventions:
• use only lowercase letters, numbers, dots (.), and underscores (_);
• prefix names with a namespace followed by a dot (e.g. kernel.);
• end names with a verb that indicates what action is being taken (e.g. request).
Here are some examples of good event names:
• kernel.response
• form.pre_set_data

Event Names and Event Objects
When the dispatcher notifies listeners, it passes an actual Event object to those listeners. The base Event
class is very simple: it contains a method for stopping event propagation, but not much else.
Often times, data about a specific event needs to be passed along with the Event object so that the
listeners have needed information. In the case of the kernel.response event, the Event object that's
created and passed to each listener is actually of type FilterResponseEvent5, a subclass of the base
Event object. This class contains methods such as getResponse and setResponse, allowing listeners to
get or even replace the Response object.
The moral of the story is this: When creating a listener to an event, the Event object that's passed to
the listener may be a special subclass that has additional methods for retrieving information from and
responding to the event.

The Dispatcher
The dispatcher is the central object of the event dispatcher system. In general, a single dispatcher is
created, which maintains a registry of listeners. When an event is dispatched via the dispatcher, it notifies
all listeners registered with that event:
Listing 25-1

Connecting Listeners
To take advantage of an existing event, you need to connect a listener to the dispatcher so that it can
be notified when the event is dispatched. A call to the dispatcher addListener() method associates any
valid PHP callable to an event:
Listing 25-2

The addListener() method takes up to three arguments:
• The event name (string) that this listener wants to listen to;
• A PHP callable that will be notified when an event is thrown that it listens to;
• An optional priority integer (higher equals more important) that determines when a listener is
triggered versus other listeners (defaults to 0). If two listeners have the same priority, they are
executed in the order that they were added to the dispatcher.
A PHP callable6 is a PHP variable that can be used by the call_user_func() function and returns
true when passed to the is_callable() function. It can be a \Closure instance, an object
implementing an __invoke method (which is what closures are in fact), a string representing a
function, or an array representing an object method or a class method.
So far, you've seen how PHP objects can be registered as listeners. You can also register PHP
Closures7 as event listeners:
Listing 25-3

Once a listener is registered with the dispatcher, it waits until the event is notified. In the above example,
when the foo.action event is dispatched, the dispatcher calls the AcmeListener::onFooAction method
and passes the Event object as the single argument:
Listing 25-4

In many cases, a special Event subclass that's specific to the given event is passed to the listener.
This gives the listener access to special information about the event. Check the documentation or
implementation of each event to determine the exact Symfony\Component\EventDispatcher\Event
instance that's being passed. For example, the kernel.event event passes an instance of
Symfony\Component\HttpKernel\Event\FilterResponseEvent:

Creating and Dispatching an Event
In addition to registering listeners with existing events, you can create and dispatch your own events.
This is useful when creating third-party libraries and also when you want to keep different components
of your own system flexible and decoupled.

The Static Events Class
Suppose you want to create a new Event - store.order - that is dispatched each time an order is created
inside your application. To keep things organized, start by creating a StoreEvents class inside your
application that serves to define and document your event:
Listing 25-6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

namespace Acme\StoreBundle;
final class StoreEvents
{
/**
* The store.order event is thrown each time an order is created
* in the system.
*
* The event listener receives an
* Acme\StoreBundle\Event\FilterOrderEvent instance.
*
* @var string
*/
const STORE_ORDER = 'store.order';
}

Notice that this class doesn't actually do anything. The purpose of the StoreEvents class is just to
be a location where information about common events can be centralized. Notice also that a special
FilterOrderEvent class will be passed to each listener of this event.

Creating an Event object
Later, when you dispatch this new event, you'll create an Event instance and pass it to the dispatcher. The
dispatcher then passes this same instance to each of the listeners of the event. If you don't need to pass
any information to your listeners, you can use the default Symfony\Component\EventDispatcher\Event
class. Most of the time, however, you will need to pass information about the event to each listener. To
accomplish this, you'll create a new class that extends Symfony\Component\EventDispatcher\Event.
In this example, each listener will need access to some pretend Order object. Create an Event class that
makes this possible:
Listing 25-7

Each listener now has access to the Order object via the getOrder method.

Dispatch the Event
The dispatch()8 method notifies all listeners of the given event. It takes two arguments: the name of the
event to dispatch and the Event instance to pass to each listener of that event:
Listing 25-8

1
2
3
4
5
6
7
8
9
10
11

use Acme\StoreBundle\StoreEvents;
use Acme\StoreBundle\Order;
use Acme\StoreBundle\Event\FilterOrderEvent;

// the order is somehow created or retrieved
$order = new Order();
// ...
// create the FilterOrderEvent and dispatch it
$event = new FilterOrderEvent($order);
$dispatcher->dispatch(StoreEvents::STORE_ORDER, $event);

Notice that the special FilterOrderEvent object is created and passed to the dispatch method. Now,
any listener to the store.order event will receive the FilterOrderEvent and have access to the Order
object via the getOrder method:
Listing 25-9

1
2
3
4
5
6
7
8

// some listener class that's been registered for "STORE_ORDER" event
use Acme\StoreBundle\Event\FilterOrderEvent;
public function onStoreOrder(FilterOrderEvent $event)
{
$order = $event->getOrder();
// do something to or with the order
}

Using Event Subscribers
The most common way to listen to an event is to register an event listener with the dispatcher. This
listener can listen to one or more events and is notified each time those events are dispatched.
8. http://api.symfony.com/2.2/Symfony/Component/EventDispatcher/EventDispatcher.html#dispatch()

PDF brought to you by
generated on March 17, 2013

Chapter 25: The Event Dispatcher Component | 97

Another way to listen to events is via an event subscriber. An event subscriber is a PHP class that's
able to tell the dispatcher exactly which events it should subscribe to. It implements the
EventSubscriberInterface9 interface, which requires a single static method called
getSubscribedEvents. Take the following example of a subscriber that subscribes to the
kernel.response and store.order events:
Listing 25-10

This is very similar to a listener class, except that the class itself can tell the dispatcher which events it
should listen to. To register a subscriber with the dispatcher, use the addSubscriber()10 method:
Listing 25-11

The dispatcher will automatically register the subscriber for each event returned by the
getSubscribedEvents method. This method returns an array indexed by event names and whose values
9. http://api.symfony.com/2.2/Symfony/Component/EventDispatcher/EventSubscriberInterface.html
10. http://api.symfony.com/2.2/Symfony/Component/EventDispatcher/EventDispatcher.html#addSubscriber()

PDF brought to you by
generated on March 17, 2013

Chapter 25: The Event Dispatcher Component | 98

are either the method name to call or an array composed of the method name to call and a priority. The
example above shows how to register several listener methods for the same event in subscriber and also
shows how to pass the priority of each listener method.

Stopping Event Flow/Propagation
In some cases, it may make sense for a listener to prevent any other listeners from being called. In other
words, the listener needs to be able to tell the dispatcher to stop all propagation of the event to future
listeners (i.e. to not notify any more listeners). This can be accomplished from inside a listener via the
stopPropagation()11 method:
Listing 25-12

Now, any listeners to store.order that have not yet been called will not be called.
It is possible to detect if an event was stopped by using the isPropagationStopped()12 method which
returns a boolean value:
Listing 25-13

EventDispatcher aware Events and Listeners
New in version 2.1: The Event object contains a reference to the invoking dispatcher since Symfony
2.1

The EventDispatcher always injects a reference to itself in the passed event object. This means that all
listeners have direct access to the EventDispatcher object that notified the listener via the passed Event
object's getDispatcher()13 method.
This can lead to some advanced applications of the EventDispatcher including letting listeners dispatch
other events, event chaining or even lazy loading of more listeners into the dispatcher object. Examples
follow:
Lazy loading listeners:
Listing 25-14

While this above is sufficient for most uses, if your application uses multiple EventDispatcher instances,
you might need to specifically inject a known instance of the EventDispatcher into your listeners. This
could be done using constructor or setter injection as follows:
Constructor injection:
Listing 25-16

Choosing between the two is really a matter of taste. Many tend to prefer the constructor injection as
the objects are fully initialized at construction time. But when you have a long list of dependencies, using
setter injection can be the way to go, especially for optional dependencies.

Dispatcher Shortcuts
New in version 2.1: EventDispatcher::dispatch() method returns the event since Symfony 2.1.

The EventDispatcher::dispatch14 method always returns an Event15 object. This allows for various
shortcuts. For example if one does not need a custom event object, one can simply rely on a plain Event16
object. You do not even need to pass this to the dispatcher as it will create one by default unless you
specifically pass one:
Listing 25-18

1 $dispatcher->dispatch('foo.event');

Moreover, the EventDispatcher always returns whichever event object that was dispatched, i.e. either the
event that was passed or the event that was created internally by the dispatcher. This allows for nice
shortcuts:
Listing 25-19

Since the EventDispatcher already knows the name of the event when dispatching it, the event name is
also injected into the Event17 objects, making it available to event listeners via the getName()18 method.
The event name, (as with any other data in a custom event object) can be used as part of the listener's
processing logic:
Listing 25-22

New in version 2.1: The GenericEvent event class was added in Symfony 2.1

The base Event1 class provided by the Event Dispatcher component is deliberately sparse to allow the
creation of API specific event objects by inheritance using OOP. This allow for elegant and readable code
in complex applications.
The GenericEvent2 is available for convenience for those who wish to use just one event object
throughout their application. It is suitable for most purposes straight out of the box, because it follows
the standard observer pattern where the event object encapsulates an event 'subject', but has the addition
of optional extra arguments.

The GenericEvent also implements ArrayAccess12 on the event arguments which makes it very
convenient to pass extra arguments regarding the event subject.
The following examples show use-cases to give a general idea of the flexibility. The examples assume
event listeners have been added to the dispatcher.
Simply passing a subject:
Listing 26-1

New in version 2.1: This feature was moved into the EventDispatcher component in Symfony 2.1.

Introduction
The ContainerAwareEventDispatcher1 is a special event dispatcher implementation which is coupled to
the service container that is part of the Dependency Injection component. It allows services to be specified
as event listeners making the event dispatcher extremely powerful.
Services are lazy loaded meaning the services attached as listeners will only be created if an event is
dispatched that requires those listeners.

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
$container = new ContainerBuilder();
$dispatcher = new ContainerAwareEventDispatcher($container);

Adding Listeners
The Container Aware Event Dispatcher can either load specified services directly, or services that
implement EventSubscriberInterface4.
The following examples assume the service container has been loaded with any services that are
mentioned.
Services must be marked as public in the container.

Adding Services
To connect existing service definitions, use the addListenerService()5 method where the $callback is
an array of array($serviceId, $methodName):
Listing 27-2

Adding Subscriber Services
EventSubscribers can be added using the addSubscriberService()6 method where the first argument
is the service ID of the subscriber service, and the second argument is the the service's class name (which
must implement EventSubscriberInterface7) as follows:
Listing 27-3

The Filesystem Component
The Filesystem components provides basic utilities for the filesystem.
New in version 2.1: The Filesystem Component is new to Symfony 2.1. Previously, the Filesystem
class was located in the HttpKernel component.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Filesystem1);
â&#x20AC;˘ Install it via Composer (symfony/filesystem on Packagist2).

Usage
The Filesystem3 class is the unique endpoint for filesystem operations:
Listing 28-1

You can pass an array or any Traversable13 object as the first argument.

Copy
This method is used to copy files. If the target already exists, the file is copied only if the source
modification date is earlier than the target. This behavior can be overridden by the third boolean
argument:
Listing 28-4

// works only if image-ICC has been modified after image.jpg
$fs->copy('image-ICC.jpg', 'image.jpg');
// image.jpg will be overridden
$fs->copy('image-ICC.jpg', 'image.jpg', true);

Touch
Touch sets access and modification time for a file. The current time is used by default. You can set your
own with the second argument. The third argument is the access time:
Listing 28-5

1
2
3
4
5
6

// set modification time to the current timestamp
$fs->touch('file.txt');
// set modification time 10 seconds in the future
$fs->touch('file.txt', time() + 10);
// set access time 10 seconds in the past
$fs->touch('file.txt', time(), time() - 10);

You can pass an array or any Traversable14 object as the first argument.

Chown
Chown is used to change the owner of a file. The third argument is a boolean recursive option:
Listing 28-6

1
2
3
4

// set the owner of the lolcat video to www-data
$fs->chown('lolcat.mp4', 'www-data');
// change the owner of the video directory recursively
$fs->chown('/video', 'www-data', true);

You can pass an array or any Traversable15 object as the first argument.

Chgrp
Chgrp is used to change the group of a file. The third argument is a boolean recursive option:
Listing 28-7

1
2
3
4

// set the group of the lolcat video to nginx
$fs->chgrp('lolcat.mp4', 'nginx');
// change the group of the video directory recursively
$fs->chgrp('/video', 'nginx', true);

Error Handling
Whenever something wrong happens, an exception implementing ExceptionInterface19 is thrown.
Prior to version 2.1, mkdir()20 returned a boolean and did not throw exceptions. As of 2.1, a
IOException21 is thrown if a directory creation fails.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Finder1);
â&#x20AC;˘ Install it via Composer (symfony/finder on Packagist2).

The $file is an instance of SplFileInfo4 which extends SplFileInfo5 to provide methods to work with
relative paths.
The above code prints the names of all the files in the current directory recursively. The Finder class uses
a fluent interface, so all methods return the Finder instance.
A Finder instance is a PHP Iterator6. So, instead of iterating over the Finder with foreach, you
can also convert it to an array with the iterator_to_array7 method, or get the number of items
with iterator_count8.

When searching through multiple locations passed to the in()9 method, a separate iterator is
created internally for every location. This means we have multiple result sets aggregated into one.
Since iterator_to_array10 uses keys of result sets by default, when converting to an array, some
keys might be duplicated and their values overwritten. This can be avoided by passing false as a
second parameter to iterator_to_array11.

Criteria
There are lots of ways to filter and sort your results.

Location
The location is the only mandatory criteria. It tells the finder which directory to use for the search:
Listing 29-2

1 $finder->in(__DIR__);

Search in several locations by chaining calls to in()12:
Listing 29-3

1 $finder->files()->in(__DIR__)->in('/elsewhere');

New in version 2.2: Wildcard support was added in version 2.2.

Use wildcard characters to search in the directories matching a pattern:
Listing 29-4

1 $finder->in('src/Symfony/*/*/Resources');

Each pattern has to resolve to at least one directory path.
Exclude directories from matching with the exclude()13 method:
4. http://api.symfony.com/2.2/Symfony/Component/Finder/SplFileInfo.html
5.
6.
7.
8.
9.
10.
11.

The comparison operator can be any of the following: >, >=, <, <=, ==, !=.
New in version 2.1: The operator != was added in version 2.1.

The target value may use magnitudes of kilobytes (k, ki), megabytes (m, mi), or gigabytes (g, gi). Those
suffixed with an i use the appropriate 2**n version in accordance with the IEC standard23.
20. http://api.symfony.com/2.2/Symfony/Component/Finder/Finder.html#path()
21. http://api.symfony.com/2.2/Symfony/Component/Finder/Finder.html#notPath()
22. http://api.symfony.com/2.2/Symfony/Component/Finder/Finder.html#size()

The comparison operator can be any of the following: >, >=, <, '<=', '=='. You can also use since or after
as an alias for >, and until or before as an alias for <.
The target value can be any date supported by the strtotime25 function.

The filter() method takes a Closure as an argument. For each matching file, it is called with the file as
a SplFileInfo28 instance. The file is excluded from the result set if the Closure returns false.

Reading contents of returned files
New in version 2.1: Method getContents() have been introduced in version 2.1.

The contents of returned files can be read with getContents()29:
Listing 29-28

The HttpFoundation Component
The HttpFoundation Component defines an object-oriented layer for the HTTP specification.
In PHP, the request is represented by some global variables ($_GET, $_POST, $_FILE, $_COOKIE,
$_SESSION, ...) and the response is generated by some functions (echo, header, setcookie, ...).
The Symfony2 HttpFoundation component replaces these default PHP global variables and functions by
an Object-Oriented layer.

Installation
You can install the component in many different ways:
• Use the official Git repository (https://github.com/symfony/HttpFoundation1);
• Install it via Composer (symfony/http-foundation on Packagist2).

Request
The most common way to create request is to base it on the current PHP global variables with
createFromGlobals()3:
Listing 30-1

all()14: Returns the parameters;
keys()15: Returns the parameter keys;
replace()16: Replaces the current parameters by a new set;
add()17: Adds parameters;
get()18: Returns a parameter by name;
set()19: Sets a parameter by name;

• has()20: Returns true if the parameter is defined;
• remove()21: Removes a parameter.
The ParameterBag22 instance also has some methods to filter the input values:
•
•
•
•
•

getAlpha()23: Returns the alphabetic characters of the parameter value;
getAlnum()24: Returns the alphabetic characters and digits of the parameter value;
getDigits()25: Returns the digits of the parameter value;
getInt()26: Returns the parameter value converted to integer;
filter()27: Filters the parameter by using the PHP filter_var() function.

All getters takes up to three arguments: the first one is the parameter name and the second one is the
default value to return if the parameter does not exist:
Listing 30-3

When PHP imports the request query, it handles request parameters like foo[bar]=bar in a special way
as it creates an array. So you can get the foo parameter and you will get back an array with a bar element.
But sometimes, you might want to get the value for the "original" parameter name: foo[bar]. This is
possible with all the ParameterBag getters like get()28 via the third argument:
Listing 30-4

Finally, you can also store additional data in the request, thanks to the public attributes property,
which is also an instance of ParameterBag29. This is mostly used to attach information that belongs to the
Request and that needs to be accessed from many different points in your application. For information
on how this is used in the Symfony2 framework, see read more.

Identifying a Request
In your application, you need a way to identify a request; most of the time, this is done via the "path info"
of the request, which can be accessed via the getPathInfo()30 method:
Listing 30-5

1 // for a request to http://example.com/blog/index.php/post/hello-world
2 // the path info is "/post/hello-world"
3 $request->getPathInfo();

Simulating a Request
Instead of creating a Request based on the PHP globals, you can also simulate a Request:
Listing 30-6

The create()31 method creates a request based on a path info, a method and some parameters (the query
parameters or the request ones depending on the HTTP method); and of course, you an also override all
other variables as well (by default, Symfony creates sensible defaults for all the PHP global variables).
Based on such a request, you can override the PHP global variables via overrideGlobals()32:
Listing 30-7

1 $request->overrideGlobals();

You can also duplicate an existing query via duplicate()33 or change a bunch of parameters with
a single call to initialize()34.

Accessing the Session
If you have a session attached to the Request, you can access it via the getSession()35 method; the
hasPreviousSession()36 method tells you if the request contains a Session which was started in one of
the previous requests.

Accessing other Data
The Request class has many other methods that you can use to access the request information. Have a
look at the API for more information about them.

Response
A Response42 object holds all the information that needs to be sent back to the client from a given request.
The constructor takes up to three arguments: the response content, the status code, and an array of
HTTP headers:
Listing 30-9

These information can also be manipulated after the Response object creation:
Listing 30-10

1
2
3
4
5
6

$response->setContent('Hello World');

// the headers public attribute is a ResponseHeaderBag
$response->headers->set('Content-Type', 'text/plain');
$response->setStatusCode(404);

When setting the Content-Type of the Response, you can set the charset, but it is better to set it via the
setCharset()43 method:
39. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Request.html#getCharsets()
40. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/AcceptHeader.html
41. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/AcceptHeader.html
42. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Response.html

PDF brought to you by
generated on March 17, 2013

Chapter 30: The HttpFoundation Component | 125

Listing 30-11

1 $response->setCharset('ISO-8859-1');

Note that by default, Symfony assumes that your Responses are encoded in UTF-8.

Sending the Response
Before sending the Response, you can ensure that it is compliant with the HTTP specification by calling
the prepare()44 method:
Listing 30-12

1 $response->prepare($request);

Sending the response to the client is then as simple as calling send()45:
Listing 30-13

1 $response->send();

Setting Cookies
The response cookies can be manipulated though the headers public attribute:
Listing 30-14

Downloading Files
New in version 2.1: The makeDisposition method was added in Symfony 2.1.

When uploading a file, you must add a Content-Disposition header to your response. While creating
this header for basic file downloads is easy, using non-ASCII filenames is more involving. The
makeDisposition()65 abstracts the hard work behind a simple API:
Listing 30-19

This encodes your array of data to JSON and sets the Content-Type header to application/json. If
you're using JSONP, you can set the callback function that the data should be passed to:
Listing 30-22

1 $response->setCallback('handleResponse');

In this case, the Content-Type header will be text/javascript and the response content will look like
this:
Listing 30-23

1 handleResponse({'data': 123});

Session
The session information is in its own document: Session Management.

PDF brought to you by
generated on March 17, 2013

Chapter 30: The HttpFoundation Component | 129

Chapter 31

Session Management
The Symfony2 HttpFoundation Component has a very powerful and flexible session subsystem which
is designed to provide session management through a simple object-oriented interface using a variety of
session storage drivers.
New in version 2.1: The SessionInterface1 interface, as well as a number of other changes, are
new as of Symfony 2.1.

Symfony sessions are designed to replace several native PHP functions. Applications should avoid
using session_start(), session_regenerate_id(), session_id(), session_name(), and
session_destroy() and instead use the APIs in the following section.

While it is recommended to explicitly start a session, a sessions will actually start on demand, that
is, if any session request is made to read/write session data.

Symfony sessions are incompatible with PHP ini directive session.auto_start = 1 This directive
should be turned off in php.ini, in the webserver directives or in .htaccess.

Session API
The Session4 class implements SessionInterface5.
The Session6 has a simple API as follows divided into a couple of groups.
Session workflow
• start()7: Starts the session - do not use session_start().
• migrate()8: Regenerates the session ID - do not use session_regenerate_id(). This method
can optionally change the lifetime of the new cookie that will be emitted by calling this
method.
• invalidate()9: Clears all session data and regenerates session ID. Do not use
session_destroy().
• getId()10: Gets the session ID. Do not use session_id().
• setId()11: Sets the session ID. Do not use session_id().
• getName()12: Gets the session name. Do not use session_name().
• setName()13: Sets the session name. Do not use session_name().
Session attributes
•
•
•
•
•

set()14: Sets an attribute by key;
get()15: Gets an attribute by key;
all()16: Gets all attributes as an array of key => value;
has()17: Returns true if the attribute exists;
keys()18: Returns an array of stored attribute keys;

• replace()19: Sets multiple attributes at once: takes a keyed array and sets each key => value
pair.
• remove()20: Deletes an attribute by key;
• clear()21: Clear all attributes;
The attributes are stored internally in an "Bag", a PHP object that acts like an array. A few methods exist
for "Bag" management:
• registerBag()22: Registers a SessionBagInterface23
• getBag()24: Gets a SessionBagInterface25 by bag name.
• getFlashBag()26: Gets the FlashBagInterface27. This is just a shortcut for convenience.
Session meta-data
• getMetadataBag()28: Gets the MetadataBag29 which contains information about the session.

Session Data Management
PHP's session management requires the use of the $_SESSION super-global, however, this interferes
somewhat with code testability and encapsulation in a OOP paradigm. To help overcome this, Symfony2
uses 'session bags' linked to the session to encapsulate a specific dataset of 'attributes' or 'flash messages'.
This approach also mitigates namespace pollution within the $_SESSION super-global because each bag
stores all its data under a unique namespace. This allows Symfony2 to peacefully co-exist with other
applications or libraries that might use the $_SESSION super-global and all data remains completely
compatible with Symfony2's session management.
Symfony2 provides 2 kinds of storage bags, with two separate implementations. Everything is written
against interfaces so you may extend or create your own bag types if necessary.

SessionBagInterface30 has the following API which is intended mainly for internal purposes:
• getStorageKey()31: Returns the key which the bag will ultimately store its array under in
$_SESSION. Generally this value can be left at its default and is for internal use.
• initialize()32: This is called internally by Symfony2 session storage classes to link bag data
to the session.
• getName()33: Returns the name of the session bag.

Attributes
The purpose of the bags implementing the AttributeBagInterface34 is to handle session attribute
storage. This might include things like user ID, and remember me login settings or other user based state
information.
• AttributeBag35 This is the standard default implementation.
• NamespacedAttributeBag36 This implementation allows for attributes to be stored in a
structured namespace.
Any plain key => value storage system is limited in the extent to which complex data can be stored
since each key must be unique. You can achieve namespacing by introducing a naming convention to
the keys so different parts of your application could operate without clashing. For example, module1.foo
and module2.foo. However, sometimes this is not very practical when the attributes data is an array, for
example a set of tokens. In this case, managing the array becomes a burden because you have to retrieve
the array then process it and store it again:
Listing 31-2

Flash messages
The purpose of the FlashBagInterface46 is to provide a way of setting and retrieving messages on a per
session basis. The usual workflow for flash messages would be set in an request, and displayed after a
page redirect. For example, a user submits a form which hits an update controller, and after processing
the controller redirects the page to either the updated page or an error page. Flash messages set in the
previous page request would be displayed immediately on the subsequent page load for that session. This
is however just one application for flash messages.
• AutoExpireFlashBag47
This implementation messages set in one page-load will be available for display only on
the next page load. These messages will auto expire regardless of if they are retrieved or
not.
• FlashBag48
In this implementation, messages will remain in the session until they are explicitly
retrieved or cleared. This makes it possible to use ESI caching.

FlashBagInterface49 has a simple API
• add()50: Adds a flash message to the stack of specified type;
• set()51: Sets flashes by type; This method conveniently takes both singles messages as a
string or multiple messages in an array.
• get()52: Gets flashes by type and clears those flashes from the bag;
• setAll()53: Sets all flashes, accepts a keyed array of arrays type => array(messages);
• all()54: Gets all flashes (as a keyed array of arrays) and clears the flashes from the bag;
• peek()55: Gets flashes by type (read only);
• peekAll()56: Gets all flashes (read only) as keyed array of arrays;
• has()57: Returns true if the type exists, false if not;
• keys()58: Returns an array of the stored flash types;
• clear()59: Clears the bag;
For simple applications it is usually sufficient to have one flash message per type, for example a
confirmation notice after a form is submitted. However, flash messages are stored in a keyed array by
flash $type which means your application can issue multiple messages for a given type. This allows the
API to be used for more complex messaging in your application.
Examples of setting multiple flashes:
Listing 31-5

Configuring Sessions and Save Handlers
This section deals with how to configure session management and fine tune it to your specific needs.
This documentation covers save handlers, which store and retrieve session data, and configuring session
behaviour.

Save Handlers
The PHP session workflow has 6 possible operations that may occur. The normal session follows open,
read, write and close, with the possibility of destroy and gc (garbage collection which will expire any old
sessions: gc is called randomly according to PHP's configuration and if called, it is invoked after the open
operation). You can read more about this at php.net/session.customhandler1

Native PHP Save Handlers
So-called 'native' handlers, are save handlers which are either compiled into PHP or provided by PHP
extensions, such as PHP-Sqlite, PHP-Memcached and so on.
All native save handlers are internal to PHP and as such, have no public facing API. They must be
configured by PHP ini directives, usually session.save_path and potentially other driver specific
directives. Specific details can be found in docblock of the setOptions() method of each class.
While native save handlers can be activated by directly using ini_set('session.save_handler',
$name);, Symfony2 provides a convenient way to activate these in the same way as custom handlers.
Symfony2 provides drivers for the following native save handler as an example:
â&#x20AC;˘ NativeFileSessionHandler2
Example usage:
Listing 32-1

1 use Symfony\Component\HttpFoundation\Session\Session;
2 use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;

With the exception of the files handler which is built into PHP and always available, the
availability of the other handlers depends on those PHP extensions being active at runtime.

Native save handlers provide a quick solution to session storage, however, in complex systems
where you need more control, custom save handlers may provide more freedom and flexibility.
Symfony2 provides several implementations which you may further customise as required.

Custom Save Handlers
Custom handlers are those which completely replace PHP's built in session save handlers by providing
six callback functions which PHP calls internally at various points in the session workflow.
Symfony2 HttpFoundation provides some by default and these can easily serve as examples if you wish
to write your own.
•
•
•
•
•

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
$storage = new NativeSessionStorage(array(), new PdoSessionHandler());
$session = new Session($storage);

Configuring PHP Sessions
The NativeSessionStorage8 can configure most of the PHP ini configuration directives which are
documented at php.net/session.configuration9.
To configure these settings, pass the keys (omitting the initial session. part of the key) as a key-value
array to the $options constructor argument. Or set them via the setOptions()10 method.
3. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.html
4. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcacheSessionHandler.html
5. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.html
6. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.html
7. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/Handler/NullSessionHandler.html
8. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.html
9. http://php.net/session.configuration
10. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.html#setOptions()

PDF brought to you by
generated on March 17, 2013

Chapter 32: Configuring Sessions and Save Handlers | 137

For the sake of clarity, some key options are explained in this documentation.

Session Cookie Lifetime
For security, session tokens are generally recommended to be sent as session cookies. You can configure
the lifetime of session cookies by specifying the lifetime (in seconds) using the cookie_lifetime key in
the constructor's $options argument in NativeSessionStorage11.
Setting a cookie_lifetime to 0 will cause the cookie to live only as long as the browser remains open.
Generally, cookie_lifetime would be set to a relatively large number of days, weeks or months. It is not
uncommon to set cookies for a year or more depending on the application.
Since session cookies are just a client-side token, they are less important in controlling the fine details of
your security settings which ultimately can only be securely controlled from the server side.
The cookie_lifetime setting is the number of seconds the cookie should live for, it is not
a Unix timestamp. The resulting session cookie will be stamped with an expiry time of
time()``+``cookie_lifetime where the time is taken from the server.

Configuring Garbage Collection
When a session opens, PHP will call the gc handler randomly according to the probability set by
session.gc_probability / session.gc_divisor. For example if these were set to 5/100 respectively, it
would mean a probability of 5%. Similarly, 3/4 would mean a 3 in 4 chance of being called, i.e. 75%.
If the garbage collection handler is invoked, PHP will pass the value stored in the PHP ini directive
session.gc_maxlifetime. The meaning in this context is that any stored session that was saved more
than maxlifetime ago should be deleted. This allows one to expire records based on idle time.
You can configure these settings by passing gc_probability, gc_divisor and gc_maxlifetime in an
array to the constructor of NativeSessionStorage12 or to the setOptions()13 method.

Session Lifetime
When a new session is created, meaning Symfony2 issues a new session cookie to the client, the cookie
will be stamped with an expiry time. This is calculated by adding the PHP runtime configuration value in
session.cookie_lifetime with the current server time.
PHP will only issue a cookie once. The client is expected to store that cookie for the entire lifetime.
A new cookie will only be issued when the session is destroyed, the browser cookie is deleted, or
the session ID is regenerated using the migrate() or invalidate() methods of the Session class.
The initial cookie lifetime can be set by configuring NativeSessionStorage using the
setOptions(array('cookie_lifetime' => 1234)) method.

A cookie lifetime of 0 means the cookie expires when the browser is closed.

Session Idle Time/Keep Alive
There are often circumstances where you may want to protect, or minimize unauthorized use of a session
when a user steps away from their terminal while logged in by destroying the session after a certain period
of idle time. For example, it is common for banking applications to log the user out after just 5 to 10
minutes of inactivity. Setting the cookie lifetime here is not appropriate because that can be manipulated
by the client, so we must do the expiry on the server side. The easiest way is to implement this via garbage
collection which runs reasonably frequently. The cookie lifetime would be set to a relatively high value,
and the garbage collection maxlifetime would be set to destroy sessions at whatever the desired idle
period is.
The other option is to specifically checking if a session has expired after the session is started. The session
can be destroyed as required. This method of processing can allow the expiry of sessions to be integrated
into the user experience, for example, by displaying a message.
Symfony2 records some basic meta-data about each session to give you complete freedom in this area.

Session meta-data
Sessions are decorated with some basic meta-data to enable fine control over the security settings.
The session object has a getter for the meta-data, getMetadataBag()14 which exposes an instance of
MetadataBag15:
Listing 32-3

PHP 5.4 compatibility
Since PHP 5.4.0, SessionHandler16 and SessionHandlerInterface17 are available. Symfony 2.1
provides forward compatibility for the SessionHandlerInterface18 so it can be used under PHP 5.3.
This greatly improves inter-operability with other libraries.

SessionHandler19 is a special PHP internal class which exposes native save handlers to PHP user-space.
In order to provide a solution for those using PHP 5.4, Symfony2 has a special class called
NativeSessionHandler20 which under PHP 5.4, extends from SessionHandler and under PHP 5.3 is just
a empty base class. This provides some interesting opportunities to leverage PHP 5.4 functionality if it is
available.

Save Handler Proxy
There are two kinds of save handler class proxies which inherit from AbstractProxy21: they are
NativeProxy22 and SessionHandlerProxy23.

NativeSessionStorage24 automatically injects storage handlers into a save handler proxy unless already
wrapped by one.
NativeProxy25 is used automatically under PHP 5.3 when internal PHP save handlers are specified using
the Native*SessionHandler classes, while SessionHandlerProxy26 will be used to wrap any custom save
handlers, that implement SessionHandlerInterface27.
Under PHP 5.4 and above, all session handlers implement SessionHandlerInterface28 including
Native*SessionHandler classes which inherit from SessionHandler29.
The proxy mechanism allows you to get more deeply involved in session save handler classes. A proxy for
example could be used to encrypt any session transaction without knowledge of the specific save handler.

Testing with Sessions
Symfony2 is designed from the ground up with code-testability in mind. In order to make your code
which utilizes session easily testable we provide two separate mock storage mechanisms for both unit
testing and functional testing.
Testing code using real sessions is tricky because PHP's workflow state is global and it is not possible to
have multiple concurrent sessions in the same PHP process.
The mock storage engines simulate the PHP session workflow without actually starting one allowing you
to test your code without complications. You may also run multiple instances in the same PHP process.
The mock storage drivers do not read or write the system globals session_id() or session_name(). Methods
are provided to simulate this if required:
•
•
•
•

Trusting Proxies
If you find yourself behind some sort of proxy - like a load balancer - then certain header information
may be sent to you using special X-Forwarded-* headers. For example, the Host HTTP header is usually
used to return the requested host. But when you're behind a proxy, the true host may be stored in a XForwarded-Host header.
Since HTTP headers can be spoofed, Symfony2 does not trust these proxy headers by default. If you are
behind a proxy, you should manually whitelist your proxy:
Listing 34-1

Not trusting certain Headers
By default, if you whitelist your proxy's IP address, then all four headers listed above are trusted. If you
need to trust some of these headers but not others, you can do that as well:
Listing 34-3

The HttpKernel Component
The HttpKernel Component provides a structured process for converting a Request into a
Response by making use of the event dispatcher. It's flexible enough to create a full-stack
framework (Symfony), a micro-framework (Silex) or an advanced CMS system (Drupal).

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/HttpKernel1);
â&#x20AC;˘ Install it via Composer (symfony/http-kernel on Packagist2).

The Workflow of a Request
Every HTTP web interaction begins with a request and ends with a response. Your job as a developer is
to create PHP code that reads the request information (e.g. the URL) and creates and returns a response
(e.g. an HTML page or JSON string).
../../_images/request-response-flow.png
Typically, some sort of framework or system is built to handle all the repetitive tasks (e.g. routing,
security, etc) so that a developer can easily build each page of the application. Exactly how these systems
are built varies greatly. The HttpKernel component provides an interface that formalizes the process of
starting with a request and creating the appropriate response. The component is meant to be the heart of
any application or framework, no matter how varied the architecture of that system:
Listing 35-1

Internally,
HttpKernel::handle()3
the
concrete
implementation
of
HttpKernelInterface::handle()4 - defines a workflow that starts with a Request5 and ends with a
Response6.
../../_images/01-workflow.png
The exact details of this workflow are the key to understanding how the kernel (and the Symfony
Framework or any other library that uses the kernel) works.

HttpKernel: Driven by Events
The HttpKernel::handle() method works internally by dispatching events. This makes the method
both flexible, but also a bit abstract, since all the "work" of a framework/application built with
HttpKernel is actually done in event listeners.
To help explain this process, this document looks at each step of the process and talks about how one
specific implementation of the HttpKernel - the Symfony Framework - works.
Initially, using the HttpKernel7 is really simple, and involves creating an event dispatcher and a controller
resolver (explained below). To complete your working kernel, you'll add more event listeners to the
events discussed below:
Listing 35-2

// actually execute the kernel, which turns the request into a response
// by dispatching events, calling a controller, and returning the response
$response = $kernel->handle($request);
// echo the content and send the headers
$response->send();
// triggers the kernel.terminate event
$kernel->terminate($request, $response);

See "A Full Working Example" for a more concrete implementation.
For general information on adding listeners to the events below, see Creating an Event Listener.
Fabien Potencier also wrote a wonderful series on using the HttpKernel component and other
Symfony2 components to create your own framework. See Create your own framework... on top of
the Symfony2 Components8.

1) The kernel.request event
Typical Purposes: To add more information to the Request, initialize parts of the system, or return a
Response if possible (e.g. a security layer that denies access)
Kernel Events Information Table
The first event that is dispatched inside HttpKernel::handle9 is kernel.request, which may have a
variety of different listeners.
../../_images/02-kernel-request.png
Listeners of this event can be quite varied. Some listeners - such as a security listener - might have enough
information to create a Response object immediately. For example, if a security listener determined that a
user doesn't have access, that listener may return a RedirectResponse10 to the login page or a 403 Access
Denied response.
If a Response is returned at this stage, the process skips directly to the kernel.response event.
../../_images/03-kernel-request-response.png
Other listeners simply initialize things or add more information to the request. For example, a listener
might determine and set the locale on the Request object.
Another common listener is routing. A router listener may process the Request and determine the
controller that should be rendered (see the next section). In fact, the Request object has an "attributes"
bag which is a perfect spot to store this extra, application-specific data about the request. This means
that if your router listener somehow determines the controller, it can store it on the Request attributes
(which can be used by your controller resolver).
Overall, the purpose of the kernel.request event is either to create and return a Response directly, or to
add information to the Request (e.g. setting the locale or setting some other information on the Request
attributes).

kernel.request in the Symfony Framework
The most important listener to kernel.request in the Symfony Framework is the
RouterListener11. This class executes the routing layer, which returns an array of information
about the matched request, including the _controller and any placeholders that are in the route's
pattern (e.g. {slug}). See Routing Component.
This array of information is stored in the Request12 object's attributes array. Adding the routing
information here doesn't do anything yet, but is used next when resolving the controller.

2) Resolve the Controller
Assuming that no kernel.request listener was able to create a Response, the next step in HttpKernel is
to determine and prepare (i.e. resolve) the controller. The controller is the part of the end-application's
code that is responsible for creating and returning the Response for a specific page. The only requirement
is that it is a PHP callable - i.e. a function, method on an object, or a Closure.
But how you determine the exact controller for a request is entirely up to your application. This is the job
of the "controller resolver" - a class that implements ControllerResolverInterface13 and is one of the
constructor arguments to HttpKernel.
../../_images/04-resolve-controller.png
Your job is to create a class that implements the interface and fill in its two methods: getController and
getArguments. In fact, one default implementation already exists, which you can use directly or learn
from: ControllerResolver14. This implementation is explained more in the sidebar below:
Listing 35-3

Internally, the HttpKernel::handle method first calls getController()15 on the controller resolver.
This method is passed the Request and is responsible for somehow determining and returning a PHP
callable (the controller) based on the request's information.
The second method, getArguments()16, will be called after another event - kernel.controller - is
dispatched.

Resolving the Controller in the Symfony2 Framework
The Symfony Framework uses the built-in ControllerResolver17 class (actually, it uses a subclass, which some extra functionality mentioned below). This class leverages the information that
was placed on the Request object's attributes property during the RouterListener.
getController
The ControllerResolver looks for a _controller key on the Request object's attributes property
(recall that this information is typically placed on the Request via the RouterListener). This
string is then transformed into a PHP callable by doing the following:
a) The AcmeDemoBundle:Default:index format of the _controller key is changed to another
string that contains the full class and method name of the controller by following the convention
used in Symfony2 - e.g. Acme\DemoBundle\Controller\DefaultController::indexAction. This
transformation is specific to the ControllerResolver18 sub-class used by the Symfony2
Framework.
b) A new instance of your controller class is instantiated with no constructor arguments.
c) If the controller implements ContainerAwareInterface19, setContainer is called on the
controller object and the container is passed to it. This step is also specific to the
ControllerResolver20 sub-class used by the Symfony2 Framework.
There are also a few other variations on the above process (e.g. if you're registering your controllers
as services).

3) The kernel.controller event
Typical Purposes: Initialize things or change the controller just before the controller is executed.
Kernel Events Information Table
After the controller callable has been determined, HttpKernel::handle dispatches the
kernel.controller event. Listeners to this event might initialize some part of the system that needs
to be initialized after certain things have been determined (e.g. the controller, routing information) but
before the controller is executed. For some examples, see the Symfony2 section below.
../../_images/06-kernel-controller.png
Listeners to this event can also change the controller callable completely by calling
FilterControllerEvent::setController21 on the event object that's passed to listeners on this event.

kernel.controller in the Symfony Framework
There are a few minor listeners to the kernel.controller event in the Symfony Framework, and
many deal with collecting profiler data when the profiler is enabled.
One interesting listener comes from the SensioFrameworkExtraBundle, which is packaged with the
Symfony Standard Edition. This listener's @ParamConverter functionality allows you to pass a full
object (e.g. a Post object) to your controller instead of a scalar value (e.g. an id parameter that
was on your route). The listener - ParamConverterListener - uses reflection to look at each of the
arguments of the controller and tries to use different methods to convert those to objects, which
are then stored in the attributes property of the Request object. Read the next section to see why
this is important.

4) Getting the Controller Arguments
Next, HttpKernel::handle calls getArguments()22. Remember that the controller returned in
getController is a callable. The purpose of getArguments is to return the array of arguments that
should be passed to that controller. Exactly how this is done is completely up to your design, though the
built-in ControllerResolver23 is a good example.
../../_images/07-controller-arguments.png
At this point the kernel has a PHP callable (the controller) and an array of arguments that should be
passed when executing that callable.

Getting the Controller Arguments in the Symfony2 Framework
Now that you know exactly what the controller callable (usually a method inside a controller
object) is, the ControllerResolver uses reflection24 on the callable to return an array of the names
of each of the arguments. It then iterates over each of these arguments and uses the following tricks
to determine which value should be passed for each argument:
a) If the Request attributes bag contains a key that matches the name of the argument, that
value is used. For example, if the first argument to a controller is $slug, and there is a slug
key in the Request attributes bag, that value is used (and typically this value came from the
RouterListener).
b) If the argument in the controller is type-hinted with Symfony's Request25 object, then the
Request is passed in as the value.

5) Calling the Controller
The next step is simple! HttpKernel::handle executes the controller.
../../_images/08-call-controller.png
The job of the controller is to build the response for the given resource. This could be an HTML page, a
JSON string or anything else. Unlike every other part of the process so far, this step is implemented by
the "end-developer", for each page that is built.
22. http://api.symfony.com/2.2/Symfony/Component/HttpKernel/Controller/ControllerResolverInterface.html#getArguments()
23. http://api.symfony.com/2.2/Symfony/Component/HttpKernel/Controller/ControllerResolver.html
24. http://php.net/manual/en/book.reflection.php
25. http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/Request.html

PDF brought to you by
generated on March 17, 2013

Chapter 35: The HttpKernel Component | 150

Usually, the controller will return a Response object. If this is true, then the work of the kernel is just
about done! In this case, the next step is the kernel.response event.
../../_images/09-controller-returns-response.png
But if the controller returns anything besides a Response, then the kernel has a little bit more work to do
- kernel.view (since the end goal is always to generate a Response object).
A controller must return something. If a controller returns null, an exception will be thrown
immediately.

6) The kernel.view event
Typical Purposes: Transform a non-Response return value from a controller into a Response
Kernel Events Information Table
If the controller doesn't return a Response object, then the kernel dispatches another event kernel.view. The job of a listener to this event is to use the return value of the controller (e.g. an array
of data or an object) to create a Response.
../../_images/10-kernel-view.png
This can be useful if you want to use a "view" layer: instead of returning a Response from the controller,
you return data that represents the page. A listener to this event could then use this data to create a
Response that is in the correct format (e.g HTML, json, etc).
At this stage, if no listener sets a response on the event, then an exception is thrown: either the controller
or one of the view listeners must always return a Response.

kernel.view in the Symfony Framework
There is no default listener inside the Symfony Framework for the kernel.view event. However,
one core bundle - SensioFrameworkExtraBundle - does add a listener to this event. If your controller
returns an array, and you place the @Template annotation above the controller, then this listener
renders a template, passes the array you returned from your controller to that template, and creates
a Response containing the returned content from that template.
Additionally, a popular community bundle FOSRestBundle26 implements a listener on this event
which aims to give you a robust view layer capable of using a single controller to return many
different content-type responses (e.g. HTML, JSON, XML, etc).

7) The kernel.response event
Typical Purposes: Modify the Response object just before it is sent
Kernel Events Information Table
The end goal of the kernel is to transform a Request into a Response. The Response might be created
during the kernel.request event, returned from the controller, or returned by one of the listeners to the
kernel.view event.
Regardless of who creates the Response, another event - kernel.response is dispatched directly
afterwards. A typical listener to this event will modify the Response object in some way, such as

26. https://github.com/friendsofsymfony/FOSRestBundle

PDF brought to you by
generated on March 17, 2013

Chapter 35: The HttpKernel Component | 151

modifying headers, adding cookies, or even changing the content of the Response itself (e.g. injecting
some JavaScript before the end </body> tag of an HTML response).
After this event is dispatched, the final Response object is returned from handle()27. In the most typical
use-case, you can then call the send()28 method, which sends the headers and prints the Response
content.

kernel.response in the Symfony Framework
There are several minor listeners on this event inside the Symfony Framework, and most modify
the response in some way. For example, the WebDebugToolbarListener29 injects some JavaScript
at the bottom of your page in the dev environment which causes the web debug toolbar to be
displayed. Another listener, ContextListener30 serializes the current user's information into the
session so that it can be reloaded on the next request.

8) The kernel.terminate event
New in version 2.1: The kernel.terminate event is new to Symfony 2.1.

Typical Purposes: To perform some "heavy" action after the response has been streamed to the user
Kernel Events Information Table
The final event of the HttpKernel process is kernel.terminate and is unique because it occurs after the
HttpKernel::handle method, and after the response is send to the user. Recall from above, then the
code that uses the kernel, ends like this:
Listing 35-4

As you can see, by calling $kernel->terminate after sending the response, you will trigger the
kernel.terminate event where you can perform certain actions that you may have delayed in order to
return the response as quickly as possible to the client (e.g. sending emails).
Using the kernel.terminate event is optional, and should only be called if your kernel
implements TerminableInterface31.

kernel.terminate in the Symfony Framework
If you use the SwiftmailerBundle with Symfony2 and use memory spooling, then the
EmailSenderListener32 is activated, which actually delivers any emails that you scheduled to send
during the request.

Handling Exceptions:: the kernel.exception event
Typical Purposes: Handle some type of exception and create an appropriate Response to return for the
exception
Kernel Events Information Table
If an exception is thrown at any point inside HttpKernel::handle, another event - kernel.exception is
thrown. Internally, the body of the handle function is wrapped in a try-catch block. When any exception
is thrown, the kernel.exception event is dispatched so that your system can somehow respond to the
exception.
../../_images/11-kernel-exception.png
Each listener to this event is passed a GetResponseForExceptionEvent33 object, which you can use to
access the original exception via the getException()34 method. A typical listener on this event will check
for a certain type of exception and create an appropriate error Response.
For example, to generate a 404 page, you might throw a special type of exception and then add a
listener on this event that looks for this exception and creates and returns a 404 Response. In fact, the
HttpKernel component comes with an ExceptionListener35, which if you choose to use, will do this
and more by default (see the sidebar below for more details).

kernel.exception in the Symfony Framework
There are two main listeners to kernel.exception when using the Symfony Framework.
ExceptionListener in HttpKernel
The first comes core to the HttpKernel component and is called ExceptionListener36. The
listener has several goals:
1) The thrown exception is converted into a FlattenException37 object, which contains all the
information about the request, but which can be printed and serialized.
2) If the original exception implements HttpExceptionInterface38, then getStatusCode and
getHeaders are called on the exception and used to populate the headers and status code of the
FlattenException object. The idea is that these are used in the next step when creating the final
response.
3) A controller is executed and passed the flattened exception. The exact controller to render is
passed as a constructor argument to this listener. This controller will return the final Response for
this error page.
ExceptionListener in Security
The other important listener is the ExceptionListener39. The goal of this listener is to handle
security exceptions and, when appropriate, help the user to authenticate (e.g. redirect to the login
page).

Creating an Event Listener
As you've seen, you can create and attach event listeners to any of the events dispatched during the
HttpKernel::handle cycle. Typically a listener is a PHP class with a method that's executed, but it can
be anything. For more information on creating and attaching event listeners, see The Event Dispatcher
Component.
The name of each of the "kernel" events is defined as a constant on the KernelEvents40 class.
Additionally, each event listener is passed a single argument, which is some sub-class of KernelEvent41.
This object contains information about the current state of the system and each event has their own event
object:
Name

A Full Working Example
When using the HttpKernel component, you're free to attach any listeners to the core events and use
any controller resolver that implements the ControllerResolverInterface48. However, the HttpKernel
component comes with some built-in listeners and a built-in ControllerResolver that can be used to
create a working example:
Listing 35-5

Sub Requests
In addition to the "main" request that's sent into HttpKernel::handle, you can also send so-called "sub
request". A sub request looks and acts like any other request, but typically serves to render just one small
portion of a page instead of a full page. You'll most commonly make sub-requests from your controller
(or perhaps from inside a template, that's being rendered by your controller).
../../_images/sub-request.png
To execute a sub request, use HttpKernel::handle, but change the second arguments as follows:
Listing 35-6

1
2
3
4
5
6
7
8
9
10
11
12

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

This creates another full request-response cycle where this new Request is transformed into a Response.
The only difference internally is that some listeners (e.g. security) may only act upon the master request.
Each listener is passed some sub-class of KernelEvent49, whose getRequestType()50 can be used to
figure out if the current request is a "master" or "sub" request.
For example, a listener that only needs to act on the master request may look like this:
Listing 35-7

The Locale Component
Locale component provides fallback code to handle cases when the intl extension is missing.
Additionally it extends the implementation of a native Locale1 class with several handy
methods.
Replacement for the following functions and classes is provided:
•
•
•
•
•
•
•

Usage
Taking advantage of the fallback code includes requiring function stubs and adding class stubs to the
autoloader.
When using the ClassLoader component following code is sufficient to supplement missing intl
extension:
Listing 36-1

// Get the country names for a locale or get all country codes
$countries = Locale::getDisplayCountries('pl');
$countryCodes = Locale::getCountries();
// Get the language names for a locale or get all language codes
$languages = Locale::getDisplayLanguages('fr');
$languageCodes = Locale::getLanguages();
// Get the locale names for a given code or get all locale codes
$locales = Locale::getDisplayLocales('en');
$localeCodes = Locale::getLocales();
// Get ICU versions
$icuVersion = Locale::getIntlIcuVersion();
$icuDataVersion = Locale::getIcuDataVersion();

The Process Component
The Process Component executes commands in sub-processes.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Process1);
â&#x20AC;˘ Install it via Composer (symfony/process on Packagist2).

Usage
The Process3 class allows you to execute a command in a sub-process:
Listing 37-1

New in version 2.2: The getIncrementalOutput() and getIncrementalErrorOutput() methods
were added in Symfony 2.2.

The getOutput() method always return the whole content of the standard output of the command and
getErrorOutput() the content of the error output. Alternatively, the getIncrementalOutput()5 and
getIncrementalErrorOutput()6 methods returns the new outputs since the last call.
When executing a long running command (like rsync-ing files to a remote server), you can give feedback
to the end user in real-time by passing an anonymous function to the run()7 method:
Listing 37-2

The PropertyAccess Component
The PropertyAccess component provides function to read and write from/to an object or array
using a simple string notation.
New in version 2.2: The PropertyAccess Component is new to Symfony 2.2. Previously, the
PropertyPath class was located in the Form component.

Installation
You can install the component in two different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/PropertyAccess1);
â&#x20AC;˘ Install it via Composer (symfony/property-access on Packagist2).

Usage
The entry point of this component is the PropertyAccess::getPropertyAccessor3 factory. This factory
will create a new instance of the PropertyAccessor4 class with the default configuration:
Listing 38-1

Accessing public properties is the last option used by PropertyAccessor. It tries to access the
value using the below methods first before using the property directly. For example, if you have a
public property that has a getter method, it will use the getter.

Using Getters
The getValue method also supports reading using getters. The method will be created using common
naming conventions for getters. It camelizes the property name (first_name becomes FirstName) and
prefixes it with get. So the actual method becomes getFirstName:
Listing 38-5

Using Hassers/Issers
And it doesn't even stop there. If there is no getter found, the accessor will look for an isser or hasser.
This method is created using the same way as getters, this means that you can do something like this:
Listing 38-6

The Routing Component
The Routing Component maps an HTTP request to a set of configuration variables.

Installation
You can install the component in many different ways:
• Use the official Git repository (https://github.com/symfony/Routing1);
• Install it via Composer (symfony/routing on Packagist2).

Usage
In order to set up a basic routing system you need three parts:
• A RouteCollection3, which contains the route definitions (instances of the class Route4)
• A RequestContext5, which has information about the request
• A UrlMatcher6, which performs the mapping of the request to a single route
Let's see a quick example. Notice that this assumes that you've already configured your autoloader to
load the Routing component:
Listing 39-1

Be careful when using $_SERVER['REQUEST_URI'], as it may include any query parameters on the
URL, which will cause problems with route matching. An easy way to solve this is to use the
HttpFoundation component as explained below.

You can add as many routes as you like to a RouteCollection7.
The RouteCollection::add()8 method takes two arguments. The first is the name of the route. The
second is a Route9 object, which expects a URL path and some array of custom variables in its
constructor. This array of custom variables can be anything that's significant to your application, and is
returned when that route is matched.
If no matching route can be found a ResourceNotFoundException10 will be thrown.
In addition to your array of custom variables, a _route key is added, which holds the name of the
matched route.

Defining routes
A full route definition can contain up to seven parts:
1. The URL path route. This is matched against the URL passed to the RequestContext, and can contain
named wildcard placeholders (e.g. {placeholders}) to match dynamic parts in the URL.
2. An array of default values. This contains an array of arbitrary values that will be returned when the
request matches the route.
3. An array of requirements. These define constraints for the values of the placeholders as regular
expressions.
4. An array of options. These contain internal settings for the route and are the least commonly needed.
5. A host. This is matched against the host of the request. See How to match a route based on the
Host for more details.
6. An array of schemes. These enforce a certain HTTP scheme (http, https).
7. An array of methods. These enforce a certain HTTP request method (HEAD, GET, POST, ...).
New in version 2.2: Host matching support was added in Symfony 2.2

Take the following route, which combines several of these ideas:
Listing 39-2

In this case, the route is matched by /archive/2012-01, because the {month} wildcard matches the
regular expression wildcard given. However, /archive/foo does not match, because "foo" fails the
month wildcard.
If you want to match all urls which start with a certain path and end in an arbitrary suffix you can
use the following route definition:
Listing 39-3

Using Prefixes
You can add routes or other instances of RouteCollection11 to another collection. This way you can
build a tree of routes. Additionally you can define a prefix, default requirements, default options and host
to all routes of a subtree with the addPrefix()12 method:
Listing 39-4

Normally you can pass the values from the $_SERVER variable to populate the RequestContext14. But If
you use the HttpFoundation component, you can use its Request15 class to feed the RequestContext16 in
a shortcut:
Listing 39-6

If you have defined a scheme, an absolute URL is generated if the scheme of the current
RequestContext18 does not match the requirement.

Load Routes from a File
You've already seen how you can easily add routes to a collection right inside PHP. But you can also load
routes from a number of different files.
The Routing component comes with a number of loader classes, each giving you the ability to load a
collection of route definitions from an external file of some format. Each loader expects a FileLocator19
instance as the constructor argument. You can use the FileLocator20 to define an array of paths in which
the loader will look for the requested files. If the file is found, the loader returns a RouteCollection21.
If you're using the YamlFileLoader, then route definitions look like this:
Listing 39-8

Besides YamlFileLoader22 there are two other loaders that work the same way:
• XmlFileLoader23
• PhpFileLoader24
If you use the PhpFileLoader25 you have to provide the name of a php file which returns a
RouteCollection26:
18. http://api.symfony.com/2.2/Symfony/Component/Routing/RequestContext.html
19. http://api.symfony.com/2.2/Symfony/Component/Config/FileLocator.html
20. http://api.symfony.com/2.2/Symfony/Component/Config/FileLocator.html
21. http://api.symfony.com/2.2/Symfony/Component/Routing/RouteCollection.html
22. http://api.symfony.com/2.2/Symfony/Component/Routing/Loader/YamlFileLoader.html
23. http://api.symfony.com/2.2/Symfony/Component/Routing/Loader/XmlFileLoader.html
24. http://api.symfony.com/2.2/Symfony/Component/Routing/Loader/PhpFileLoader.html
25. http://api.symfony.com/2.2/Symfony/Component/Routing/Loader/PhpFileLoader.html

Routes as Annotations
Last but not least there are AnnotationDirectoryLoader29 and AnnotationFileLoader30 to load route
definitions from class annotations. The specific details are left out here.

The all-in-one Router
The Router31 class is a all-in-one package to quickly use the Routing component. The constructor expects
a loader instance, a path to the main route definition and some other settings:
Listing 39-12

With the cache_dir option you can enable route caching (if you provide a path) or disable caching (if it's
set to null). The caching is done automatically in the background if you want to use it. A basic example
of the Router32 class would look like:

Both routes match the same path /, however the first one will match only if the host is m.example.com.

Placeholders and Requirements in Hostname Patterns
If you're using the DependencyInjection Component (or the full Symfony2 Framework), then you can use
service container parameters as variables anywhere in your routes.
You can avoid hardcoding the domain name by using a placeholder and a requirement. The %domain% in
requirements is replaced by the value of the domain dependency injection container parameter.
Listing 40-2

The host hello.example.com will be set on each route loaded from the new routing resource.

PDF brought to you by
generated on March 17, 2013

Chapter 40: How to match a route based on the Host | 174

Chapter 41

The Security Component

Introduction
The Security Component provides a complete security system for your web application. It ships with
facilities for authenticating using HTTP basic or digest authentication, interactive form login or X.509
certificate login, but also allows you to implement your own authentication strategies. Furthermore,
the component provides ways to authorize authenticated users based on their roles, and it contains an
advanced ACL system.

Installation
You can install the component in many different ways:
• Use the official Git repository (https://github.com/symfony/Security1);
• Install it via Composer (symfony/security on Packagist2).

The Firewall and Security Context
Central to the Security Component is the security context, which is an instance of
SecurityContextInterface1. When all steps in the process of authenticating the user have been taken
successfully, you can ask the security context if the authenticated user has access to a certain action or
resource of the application:
Listing 42-1

1
2
3
4
5
6
7
8
9
10

use Symfony\Component\Security\SecurityContext;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
$securityContext = new SecurityContext();

A Firewall for HTTP Requests
Authenticating a user is done by the firewall. An application may have multiple secured areas, so the
firewall is configured using a map of these secured areas. For each of these areas, the map contains a
request matcher and a collection of listeners. The request matcher gives the firewall the ability to find out
if the current request points to a secured area. The listeners are then asked if the current request can be
used to authenticate the user:
Listing 42-2

1
2
3
4
5
6

use Symfony\Component\Security\Http\FirewallMap;
use Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
$map = new FirewallMap();

The firewall is registered to listen to the kernel.request event that will be dispatched by the HttpKernel
at the beginning of each request it processes. This way, the firewall may prevent the user from going any
further than allowed.

Firewall listeners
When the firewall gets notified of the kernel.request event, it asks the firewall map if the request
matches one of the secured areas. The first secured area that matches the request will return a set of
corresponding firewall listeners (which each implement ListenerInterface3). These listeners will all
be asked to handle the current request. This basically means: find out if the current request contains
any information by which the user might be authenticated (for instance the Basic HTTP authentication
listener checks if the request has a header called PHP_AUTH_USER).

Exception listener
If any of the listeners throws an AuthenticationException4, the exception listener that was provided
when adding secured areas to the firewall map will jump in.
The exception listener determines what happens next, based on the arguments it received when it
was created. It may start the authentication procedure, perhaps ask the user to supply his credentials
again (when he has only been authenticated based on a "remember-me" cookie), or transform the
exception into an AccessDeniedHttpException5, which will eventually result in an "HTTP/1.1 403:
Access Denied" response.

Entry points
When the user is not authenticated at all (i.e. when the security context has no token yet), the firewall's
entry point will be called to "start" the authentication process. An entry point should implement
AuthenticationEntryPointInterface6, which has only one method: start()7. This method receives
2. http://api.symfony.com/2.2/Symfony/Component/HttpKernel/HttpKernel.html
3. http://api.symfony.com/2.2/Symfony/Component/Security/Http/Firewall/ListenerInterface.html
4. http://api.symfony.com/2.2/Symfony/Component/Security/Core/Exception/AuthenticationException.html
5. http://api.symfony.com/2.2/Symfony/Component/HttpKernel/Exception/AccessDeniedHttpException.html

PDF brought to you by
generated on March 17, 2013

Chapter 42: The Firewall and Security Context | 177

the current Request8 object and the exception by which the exception listener was triggered. The method
should return a Response9 object. This could be, for instance, the page containing the login form or, in
the case of Basic HTTP authentication, a response with a WWW-Authenticate header, which will prompt
the user to supply his username and password.

Flow: Firewall, Authentication, Authorization
Hopefully you can now see a little bit about how the "flow" of the security context works:
1. the Firewall is registered as a listener on the kernel.request event;
2. at the beginning of the request, the Firewall checks the firewall map to see if any firewall should
be active for this URL;
3. If a firewall is found in the map for this URL, its listeners are notified
4. each listener checks to see if the current request contains any authentication information - a
listener may (a) authenticate a user, (b) throw an AuthenticationException, or (c) do nothing
(because there is no authentication information on the request);
5. Once a user is authenticated, you'll use Authorization to deny access to certain resources.
Read the next sections to find out more about Authentication and Authorization.

Authentication
When a request points to a secured area, and one of the listeners from the firewall map is able to
extract the user's credentials from the current Request1 object, it should create a token, containing these
credentials. The next thing the listener should do is ask the authentication manager to validate the given
token, and return an authenticated token if the supplied credentials were found to be valid. The listener
should then store the authenticated token in the security context:
Listing 43-1

The AuthenticationProviderManager, when instantiated, receives several authentication providers,
each supporting a different type of token.
You may of course write your own authentication manager, it only has to implement
AuthenticationManagerInterface4.

Authentication providers
Each provider (since it implements AuthenticationProviderInterface5) has a method supports()6
by which the AuthenticationProviderManager can determine if it supports the given token. If this
is
the
case,
the
manager
then
calls
the
provider's
method
AuthenticationProviderInterface::authenticate7. This method should return an authenticated
token or throw an AuthenticationException8 (or any other exception extending it).

Authenticating Users by their Username and Password
An authentication provider will attempt to authenticate a user based on the credentials he provided.
Usually these are a username and a password. Most web applications store their user's username and
a hash of the user's password combined with a randomly generated salt. This means that the average
authentication would consist of fetching the salt and the hashed password from the user data storage,
hash the password the user has just provided (e.g. using a login form) with the salt and compare both to
determine if the given password is valid.
This functionality is offered by the DaoAuthenticationProvider9. It fetches the user's data from a
UserProviderInterface`10, uses a PasswordEncoderInterface11 to create a hash of the password and
returns an authenticated token if the password was valid:
Listing 43-3

The example above demonstrates the use of the "in-memory" user provider, but you may use any
user provider, as long as it implements UserProviderInterface12. It is also possible to let multiple
user providers try to find the user's data, using the ChainUserProvider13.

The Password encoder Factory
The DaoAuthenticationProvider14 uses an encoder factory to create a password encoder for a given
type of user. This allows you to use different encoding strategies for different types of users. The default
EncoderFactory15 receives an array of encoders:
Listing 43-4

Each encoder should implement PasswordEncoderInterface16 or be an array with a class and an
arguments key, which allows the encoder factory to construct the encoder only when it is needed.

Password Encoders
When the getEncoder()17 method of the password encoder factory is called with the user object as its
first argument, it will return an encoder of type PasswordEncoderInterface18 which should be used to
encode this user's password:
Listing 43-5

Authorization
When any of the authentication providers (see Authentication providers) has verified the stillunauthenticated token, an authenticated token will be returned. The authentication listener should set
this token directly in the SecurityContextInterface1 using its setToken()2 method.
From then on, the user is authenticated, i.e. identified. Now, other parts of the application can use the
token to decide whether or not the user may request a certain URI, or modify a certain object. This
decision will be made by an instance of AccessDecisionManagerInterface3.
An authorization decision will always be based on a few things:
• The current token
For instance, the token's getRoles()4 method may be used to retrieve the roles of the
current user (e.g. ROLE_SUPER_ADMIN), or a decision may be based on the class of the
token.
• A set of attributes
Each attribute stands for a certain right the user should have, e.g. ROLE_ADMIN to make
sure the user is an administrator.
• An object (optional)
Any object on which for which access control needs to be checked, like an article or a
comment object.

Access Decision Manager
Since deciding whether or not a user is authorized to perform a certain action can be a complicated
process, the standard AccessDecisionManager5 itself depends on multiple voters, and makes a final

verdict based on all the votes (either positive, negative or neutral) it has received. It recognizes several
strategies:
• affirmative (default)
grant access as soon as any voter returns an affirmative response;
• consensus
grant access if there are more voters granting access than there are denying;
• unanimous
only grant access if none of the voters has denied access;
Listing 44-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;

// instances of Symfony\Component\Security\Core\Authorization\Voter\VoterInterface
$voters = array(...);
// one of "affirmative", "consensus", "unanimous"
$strategy = ...;
// whether or not to grant access when all voters abstain
$allowIfAllAbstainDecisions = ...;
// whether or not to grant access when there is no majority (applies only to the
"consensus" strategy)
$allowIfEqualGrantedDeniedDecisions = ...;
$accessDecisionManager = new AccessDecisionManager(
$voters,
$strategy,
$allowIfAllAbstainDecisions,
$allowIfEqualGrantedDeniedDecisions
);

Voters
Voters are instances of VoterInterface6, which means they have to implement a few methods which
allows the decision manager to use them:
• supportsAttribute($attribute)
will be used to check if the voter knows how to handle the given attribute;
• supportsClass($class)
will be used to check if the voter is able to grant or deny access for an object of the given
class;
• vote(TokenInterface $token, $object, array $attributes)
this method will do the actual voting and return a value equal to one of the class
constants
of
VoterInterface7,
i.e.
VoterInterface::ACCESS_GRANTED,
VoterInterface::ACCESS_DENIED or VoterInterface::ACCESS_ABSTAIN;

The security component contains some standard voters which cover many use cases:

AuthenticatedVoter
The
AuthenticatedVoter8
voter
supports
the
attributes
IS_AUTHENTICATED_FULLY,
IS_AUTHENTICATED_REMEMBERED, and IS_AUTHENTICATED_ANONYMOUSLY and grants access based on the
current level of authentication, i.e. is the user fully authenticated, or only based on a "remember-me"
cookie, or even authenticated anonymously?
Listing 44-2

RoleVoter
The RoleVoter9 supports attributes starting with ROLE_ and grants access to the user when the required
ROLE_* attributes can all be found in the array of roles returned by the token's getRoles()10 method:
Listing 44-3

RoleHierarchyVoter
The RoleHierarchyVoter11 extends RoleVoter12 and provides some additional functionality: it knows
how to handle a hierarchy of roles. For instance, a ROLE_SUPER_ADMIN role may have subroles
ROLE_ADMIN and ROLE_USER, so that when a certain object requires the user to have the ROLE_ADMIN
role, it grants access to users who in fact have the ROLE_ADMIN role, but also to users having the
ROLE_SUPER_ADMIN role:
Listing 44-4

When you make your own voter, you may of course use its constructor to inject any dependencies
it needs to come to a decision.

Roles
Roles are objects that give expression to a certain right the user has. The only requirement is that they
implement RoleInterface13, which means they should also have a getRole()14 method that returns a
string representation of the role itself. The default Role15 simply returns its first constructor argument:
Listing 44-5

1
2
3
4
5
6

use Symfony\Component\Security\Core\Role\Role;
$role = new Role('ROLE_ADMIN');

// will echo 'ROLE_ADMIN'
echo $role->getRole();

Most authentication tokens extend from AbstractToken16, which means that the roles given to its
constructor will be automatically converted from strings to these simple Role objects.

Using the decision manager
The Access Listener
The access decision manager can be used at any point in a request to decide whether or not the current
user is entitled to access a given resource. One optional, but useful, method for restricting access based
on a URL pattern is the AccessListener17, which is one of the firewall listeners (see Firewall listeners)
that is triggered for each request matching the firewall map (see A Firewall for HTTP Requests).
It uses an access map (which should be an instance of AccessMapInterface18) which contains request
matchers and a corresponding set of attributes that are required for the current user to get access to the
application:
Listing 44-6

Security context
The access decision manager is also available to other parts of the application via the isGranted()19
method of the SecurityContext20. A call to this method will directly delegate the question to the access
decision manager:
Listing 44-7

The Serializer Component
The Serializer Component is meant to be used to turn objects into a specific format (XML,
JSON, Yaml, ...) and the other way around.
In order to do so, the Serializer Component follows the following simple schema.

As you can see in the picture above, an array is used as a man in the middle. This way, Encoders will only
deal with turning specific formats into arrays and vice versa. The same way, Normalizers will deal with
turning specific objects into arrays and vice versa.
Serialization is a complicated topic, and while this component may not work in all cases, it can be a useful
tool while developing tools to serialize and deserialize your objects.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Serializer1);
â&#x20AC;˘ Install it via Composer (symfony/serializer on Packagist2).
PDF brought to you by
generated on March 17, 2013

Chapter 45: The Serializer Component | 189

Usage
Using the Serializer component is really simple. You just need to set up the Serializer3 specifying which
Encoders and Normalizer are going to be available:
Listing 45-1

In this case, deserialize()6 needs three parameters:
1. The information to be decoded
2. The name of the class this information will be decoded to
3. The encoder used to convert that information into an array

JMSSerializer
A popular third-party library, JMS serializer7, provides a more sophisticated albeit more complex
solution. This library includes the ability to configure how your objects should be serialize/deserialized
via annotations (as well as YML, XML and PHP), integration with the Doctrine ORM, and handling of
other complex cases (e.g. circular references).

The Stopwatch Component
Stopwatch component provides a way to profile code.
New in version 2.2: The Stopwatch Component is new to Symfony 2.2. Previously, the Stopwatch
class was located in the HttpKernel component (and was new in 2.1).

Installation
You can install the component in two different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Stopwatch1);
â&#x20AC;˘ Install it via Composer (symfony/stopwatch on Packagist2).

Usage
The Stopwatch component provides an easy and consistent way to measure execution time of certain
parts of code so that you don't constantly have to parse microtime by yourself. Instead, use the simple
Stopwatch3 class:
Listing 46-1

You can consider categories as a way of tagging events. For example, the Symfony Profiler tool uses
categories to nicely color-code different events.

Periods
As you know from the real world, all stopwatches come with two buttons: one to start and stop
the stopwatch, and another to measure the lap time. This is exactly what the
:method:Symfony\\Component\\Stopwatch\\Stopwatch::lap method does:
Listing 46-3

Returns the category the event was started in
Returns the event start time in milliseconds
Stops all periods not already stopped
Returns the start time of the very first period
Returns the end time of the very last period
Returns the event duration, including all periods
Returns the max memory usage of all periods

Sections
Sections are a way to logically split the timeline into groups. You can see how Symfony uses sections to
nicely visualize the framework lifecycle in the Symfony Profiler tool. Here is a basic usage example using
sections:
Listing 46-6

The Templating Component
Templating provides all the tools needed to build any kind of template system.
It provides an infrastructure to load template files and optionally monitor them for changes. It
also provides a concrete template engine implementation using PHP with additional tools for
escaping and separating templates into blocks and layouts.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Templating1);
â&#x20AC;˘ Install it via Composer (symfony/templating on Packagist2).

Usage
The PhpEngine3 class is the entry point of the component. It needs a template name parser
(TemplateNameParserInterface4) to convert a template name to a template reference and template
loader (LoaderInterface5) to find the template associated to a reference:
Listing 47-1

Multiple levels of inheritance is possible: a layout can extend an other layout.

Output Escaping
This documentation is still being written.

The Asset Helper
This documentation is still being written.

PDF brought to you by
generated on March 17, 2013

Chapter 47: The Templating Component | 197

Chapter 48

The YAML Component
The YAML Component loads and dumps YAML files.

What is it?
The Symfony2 YAML Component parses YAML strings to convert them to PHP arrays. It is also able to
convert PHP arrays to YAML strings.
YAML1, YAML Ain't Markup Language, is a human friendly data serialization standard for all
programming languages. YAML is a great format for your configuration files. YAML files are as
expressive as XML files and as readable as INI files.
The Symfony2 YAML Component implements the YAML 1.2 version of the specification.
Learn more about the Yaml component in the The YAML Format article.

Installation
You can install the component in many different ways:
â&#x20AC;˘ Use the official Git repository (https://github.com/symfony/Yaml2);
â&#x20AC;˘ Install it via Composer (symfony/yaml on Packagist3).

Why?
Fast
One of the goal of Symfony YAML is to find the right balance between speed and features. It supports
just the needed feature to handle configuration files.

Real Parser
It sports a real parser and is able to parse a large subset of the YAML specification, for all your
configuration needs. It also means that the parser is pretty robust, easy to understand, and simple enough
to extend.

Clear error messages
Whenever you have a syntax problem with your YAML files, the library outputs a helpful message with
the filename and the line number where the problem occurred. It eases the debugging a lot.

Dump support
It is also able to dump PHP arrays to YAML with object support, and inline level configuration for pretty
outputs.

Types Support
It supports most of the YAML built-in types like dates, integers, octals, booleans, and much more...

Full merge key support
Full support for references, aliases, and full merge key. Don't repeat yourself by referencing common
configuration bits.

Using the Symfony2 YAML Component
The Symfony2 YAML Component is very simple and consists of two main classes: one parses YAML
strings (Parser4), and the other dumps a PHP array to a YAML string (Dumper5).
On top of these two classes, the Yaml6 class acts as a thin wrapper that simplifies common uses.

Reading YAML Files
The parse()7 method parses a YAML string and converts it to a PHP array:
Listing 48-1

The parse()10 static method takes a YAML string or a file containing YAML. Internally, it calls the
parse()11 method, but enhances the error if something goes wrong by adding the filename to the
message.

Executing PHP Inside YAML Files
New in version 2.1: The Yaml::enablePhpParsing() method is new to Symfony 2.1. Prior to 2.1,
PHP was always executed when calling the parse() function.

By default, if you include PHP inside a YAML file, it will not be parsed. If you do want PHP to be parsed,
you must call Yaml::enablePhpParsing() before parsing the file to activate this mode. If you only want
to allow PHP code for a single YAML file, be sure to disable PHP parsing after parsing the single file by
calling Yaml::$enablePhpParsing = false; ($enablePhpParsing is a public property).

The YAML Format
According to the official YAML1 website, YAML is "a human friendly data serialization standard for all
programming languages".
Even if the YAML format can describe complex nested data structure, this chapter only describes the
minimum set of features needed to use YAML as a configuration file format.
YAML is a simple language that describes data. As PHP, it has a syntax for simple types like strings,
booleans, floats, or integers. But unlike PHP, it makes a difference between arrays (sequences) and hashes
(mappings).

Scalars
The syntax for scalars is similar to the PHP syntax.

Strings
Listing 49-1

1 A string in YAML

Listing 49-2

1 'A singled-quoted string in YAML'

In a single quoted string, a single quote ' must be doubled:
Listing 49-3

Listing 49-4

1 'A single quote '' in a single-quoted string'

1 "A double-quoted string in YAML\n"

1. http://yaml.org/

PDF brought to you by
generated on March 17, 2013

Chapter 49: The YAML Format | 202

Quoted styles are useful when a string starts or ends with one or more relevant spaces.
The double-quoted style provides a way to express arbitrary strings, by using \ escape sequences.
It is very useful when you need to embed a \n or a unicode character in a string.

When a string contains line breaks, you can use the literal style, indicated by the pipe (|), to indicate that
the string will span several lines. In literals, newlines are preserved:
Listing 49-5

1 |
2
\/ /| |\/| |
3
/ / | | | |__

Alternatively, strings can be written with the folded style, denoted by >, where each line break is replaced
by a space:
Listing 49-6

1 >
2
This is a very long sentence
3
that spans several lines in the YAML
4
but which will be rendered as a string
5
without carriage returns.

Notice the two spaces before each line in the previous examples. They won't appear in the resulting
PHP strings.

Numbers
Listing 49-7

1 # an integer
2 12

Listing 49-8

1 # an octal
2 014

Listing 49-9

1 # an hexadecimal
2 0xC

Listing 49-10

1 # a float
2 13.4

Listing 49-11

1 # an exponential number
2 1.2e+34

Listing 49-12

1 # infinity
2 .inf

PDF brought to you by
generated on March 17, 2013

Chapter 49: The YAML Format | 203

Nulls
Nulls in YAML can be expressed with null or -.

Booleans
Booleans in YAML are expressed with true and false.

Dates
YAML uses the ISO-8601 standard to express dates:
Listing 49-13

1 2001-12-14t21:59:43.10-05:00

Listing 49-14

1 # simple date
2 2002-12-14

Collections
A YAML file is rarely used to describe a simple scalar. Most of the time, it describes a collection. A
collection can be a sequence or a mapping of elements. Both sequences and mappings are converted to
PHP arrays.
Sequences use a dash followed by a space:
Listing 49-15

1 - PHP
2 - Perl
3 - Python

The previous YAML file is equivalent to the following PHP code:
Listing 49-16

1 array('PHP', 'Perl', 'Python');

Mappings use a colon followed by a space (: ) to mark each key/value pair:
Listing 49-17

1 PHP: 5.2
2 MySQL: 5.1
3 Apache: 2.2.20

which is equivalent to this PHP code:
Listing 49-18

1 array('PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20');

In a mapping, a key can be any valid scalar.

The number of spaces between the colon and the value does not matter:
Listing 49-19

PDF brought to you by
generated on March 17, 2013

Chapter 49: The YAML Format | 204

1 PHP:
5.2
2 MySQL: 5.1
3 Apache: 2.2.20

YAML uses indentation with one or more spaces to describe nested collections:
Listing 49-20

There is one important thing you need to remember when using indentation in a YAML file: Indentation
must be done with one or more spaces, but never with tabulations.
You can nest sequences and mappings as you like:
Listing 49-22

YAML can also use flow styles for collections, using explicit indicators rather than indentation to denote
scope.
A sequence can be written as a comma separated list within square brackets ([]):
Listing 49-23

1 [PHP, Perl, Python]

A mapping can be written as a comma separated list of key/values within curly braces ({}):
Listing 49-24

1 { PHP: 5.2, MySQL: 5.1, Apache: 2.2.20 }

You can mix and match styles to achieve a better readability:
Listing 49-25