Symfony Cookbook 2.7
Symfony Cookbook 2.7
Symfony Cookbook 2.7
Version: 2.7
generated on July 28, 2016
Contents at a Glance
How to Use Assetic for Asset Management ..........................................................................................7
Combining, Compiling and Minimizing Web Assets with PHP Libraries.............................................13
How to Minify CSS/JS Files (Using UglifyJS and UglifyCSS) ...............................................................16
How to Minify JavaScripts and Stylesheets with YUI Compressor.......................................................20
How to Use Assetic for Image Optimization with Twig Functions ......................................................22
How to Apply an Assetic Filter to a specific File Extension .................................................................24
How to Install 3rd Party Bundles .......................................................................................................26
Best Practices for Reusable Bundles ...................................................................................................29
How to Use Bundle Inheritance to Override Parts of a Bundle ............................................................36
How to Override any Part of a Bundle ...............................................................................................38
How to Remove the AcmeDemoBundle .............................................................................................41
How to Load Service Configuration inside a Bundle ...........................................................................44
How to Create Friendly Configuration for a Bundle ...........................................................................47
How to Simplify Configuration of multiple Bundles ...........................................................................53
How to Use Varnish to Speed up my Website ....................................................................................55
Caching Pages that Contain CSRF Protected Forms ...........................................................................59
Installing Composer ..........................................................................................................................60
How to Master and Create new Environments ...................................................................................61
How to Override Symfony's default Directory Structure .....................................................................66
Using Parameters within a Dependency Injection Class ......................................................................69
Understanding how the Front Controller, Kernel and Environments Work together............................71
How to Set external Parameters in the Service Container ....................................................................74
How to Use the Apache Router .........................................................................................................76
Configuring a Web Server .................................................................................................................79
How to Organize Configuration Files ................................................................................................85
How to Create a Console Command .................................................................................................89
How to Use the Console....................................................................................................................93
How to Style a Console Command ....................................................................................................95
How to Call a Command from a Controller ..................................................................................... 102
How to Generate URLs from the Console ........................................................................................ 104
How to Enable Logging in Console Commands ............................................................................... 106
How to Define Commands as Services ............................................................................................. 110
How to Customize Error Pages ........................................................................................................ 112
How to Define Controllers as Services ............................................................................................. 117
How to Upload Files ....................................................................................................................... 122
How to Optimize your Development Environment for Debugging.................................................... 128
PDF brought to you by
generated on July 28, 2016
iv | Contents at a Glance
Contents at a Glance | 4
Contents at a Glance | v
How to Inject Variables into all Templates (i.e. global Variables) ...................................................... 441
How to Use and Register Namespaced Twig Paths ........................................................................... 443
How to Use PHP instead of Twig for Templates............................................................................... 445
How to Write a custom Twig Extension .......................................................................................... 450
How to Render a Template without a custom Controller.................................................................. 452
How to Simulate HTTP Authentication in a Functional Test ............................................................ 454
How to Simulate Authentication with a Token in a Functional Test.................................................. 455
How to Test the Interaction of several Clients .................................................................................. 457
How to Use the Profiler in a Functional Test.................................................................................... 458
How to Test Code that Interacts with the Database.......................................................................... 460
How to Test Doctrine Repositories .................................................................................................. 463
How to Customize the Bootstrap Process before Running Tests........................................................ 465
Upgrading a Patch Version (e.g. 2.6.0 to 2.6.1) ................................................................................ 467
Upgrading a Minor Version (e.g. 2.5.3 to 2.6.1) ............................................................................... 468
Upgrading a Major Version (e.g. 2.7.0 to 3.0.0)................................................................................ 470
Upgrading a Third-Party Bundle for a Major Symfony Version ......................................................... 474
How to Create a custom Validation Constraint ................................................................................ 478
How to Handle Different Error Levels.............................................................................................. 482
How to Dynamically Configure Validation Groups .......................................................................... 484
How to Use PHP's built-in Web Server ............................................................................................ 486
How to Create a SOAP Web Service in a Symfony Controller ........................................................... 489
How to Create and Store a Symfony Project in Git ........................................................................... 492
How to Create and Store a Symfony Project in Subversion................................................................ 495
Using Symfony with Homestead/Vagrant......................................................................................... 499
vi | Contents at a Glance
Contents at a Glance | 6
Chapter 1
But with Assetic, you can manipulate these assets however you want (or load them from anywhere) before
serving them. This means you can:
Minify and combine all of your CSS and JS files
Run all (or just some) of your CSS or JS files through some sort of compiler, such as LESS, SASS or
CoffeeScript
Run image optimizations on your images
Assets
Using Assetic provides many advantages over directly serving the files. The files do not need to be stored
where they are served from and can be drawn from various sources such as from within a bundle.
You can use Assetic to process CSS stylesheets, JavaScript files and images. The philosophy behind
adding either is basically the same, but with a slightly different syntax.
1
2
3
{% javascripts '@AppBundle/Resources/public/js/*' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
If your application templates use the default block names from the Symfony Standard Edition, the
javascripts tag will most commonly live in the javascripts block:
Listing 1-3
1
2
3
4
5
6
7
{# ... #}
{% block javascripts %}
{% javascripts '@AppBundle/Resources/public/js/*' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
{# ... #}
You can also include CSS stylesheets: see Including CSS Stylesheets.
In this example, all files in the Resources/public/js/ directory of the AppBundle will be loaded and
served from a different location. The actual rendered tag might simply look like:
Listing 1-4
<script src="/app_dev.php/js/abcd123.js"></script>
This is a key point: once you let Assetic handle your assets, the files are served from a different location.
This will cause problems with CSS files that reference images by their relative path. See Fixing CSS Paths
with the cssrewrite Filter.
1
2
3
If your application templates use the default block names from the Symfony Standard Edition, the
stylesheets tag will most commonly live in the stylesheets block:
Listing 1-6
1
2
3
4
5
6
7
{# ... #}
{% block stylesheets %}
{% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
{% endblock %}
{# ... #}
But because Assetic changes the paths to your assets, this will break any background images (or other
paths) that uses relative paths, unless you use the cssrewrite filter.
Notice that in the original example that included JavaScript files, you referred to the files using
a path like @AppBundle/Resources/public/file.js, but that in this example, you referred
to the CSS files using their actual, publicly-accessible path: bundles/app/css. You can use
either, except that there is a known issue that causes the cssrewrite filter to fail when using the
@AppBundle syntax for CSS stylesheets.
Including Images
To include an image you can use the image tag.
Listing 1-7
1
2
3
{% image '@AppBundle/Resources/public/images/example.jpg' %}
<img src="{{ asset_url }}" alt="Example" />
{% endimage %}
You can also use Assetic for image optimization. More information in How to Use Assetic for Image
Optimization with Twig Functions.
Instead of using Assetic to include images, you may consider using the LiipImagineBundle1
community bundle, which allows to compress and manipulate images (rotate, resize, watermark,
etc.) before serving them.
Combining Assets
One feature of Assetic is that it will combine many files into one. This helps to reduce the number of
HTTP requests, which is great for front-end performance. It also allows you to maintain the files more
easily by splitting them into manageable parts. This can help with re-usability as you can easily split
project-specific files from those which can be used in other applications, but still serve them as a single
file:
Listing 1-8
1
2
3
4
5
6
{% javascripts
'@AppBundle/Resources/public/js/*'
'@AcmeBarBundle/Resources/public/js/form.js'
'@AcmeBarBundle/Resources/public/js/calendar.js' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
In the dev environment, each file is still served individually, so that you can debug problems more easily.
However, in the prod environment (or more specifically, when the debug flag is false), this will be
rendered as a single script tag, which contains the contents of all of the JavaScript files.
If you're new to Assetic and try to use your application in the prod environment (by using the
app.php controller), you'll likely see that all of your CSS and JS breaks. Don't worry! This is on
purpose. For details on using Assetic in the prod environment, see Dumping Asset Files.
And combining files doesn't only apply to your files. You can also use Assetic to combine third party
assets, such as jQuery, with your own into a single file:
1. https://github.com/liip/LiipImagineBundle
Listing 1-9
1
2
3
4
5
{% javascripts
'@AppBundle/Resources/public/js/thirdparty/jquery.js'
'@AppBundle/Resources/public/js/*' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
1
2
3
4
5
6
7
# app/config/config.yml
assetic:
assets:
jquery_and_ui:
inputs:
- '@AppBundle/Resources/public/js/thirdparty/jquery.js'
- '@AppBundle/Resources/public/js/thirdparty/jquery.ui.js'
After you have defined the named assets, you can reference them in your templates with the
@named_asset notation:
Listing 1-11
1
2
3
4
5
{% javascripts
'@jquery_and_ui'
'@AppBundle/Resources/public/js/*' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
Filters
Once they're managed by Assetic, you can apply filters to your assets before they are served. This includes
filters that compress the output of your assets for smaller file sizes (and better frontend optimization).
Other filters can compile CoffeeScript files to JavaScript and process SASS into CSS. In fact, Assetic has a
long list of available filters.
Many of the filters do not do the work directly, but use existing third-party libraries to do the heavylifting. This means that you'll often need to install a third-party library to use a filter. The great advantage
of using Assetic to invoke these libraries (as opposed to using them directly) is that instead of having to
run them manually after you work on the files, Assetic will take care of this for you and remove this step
altogether from your development and deployment processes.
To use a filter, you first need to specify it in the Assetic configuration. Adding a filter here doesn't mean
it's being used - it just means that it's available to use (you'll use the filter below).
For example to use the UglifyJS JavaScript minifier the following configuration should be defined:
Listing 1-12
1
2
3
4
5
# app/config/config.yml
assetic:
filters:
uglifyjs2:
bin: /usr/local/bin/uglifyjs
Now, to actually use the filter on a group of JavaScript files, add it into your template:
Listing 1-13
1
2
3
A more detailed guide about configuring and using Assetic filters as well as details of Assetic's debug
mode can be found in How to Minify CSS/JS Files (Using UglifyJS and UglifyCSS).
1
2
3
Symfony also contains a method for cache busting, where the final URL generated by Assetic
contains a query parameter that can be incremented via configuration on each deployment. For more
information, see the version configuration option.
<script src="/js/abcd123.js"></script>
Moreover, that file does not actually exist, nor is it dynamically rendered by Symfony (as the asset files
are in the dev environment). This is on purpose - letting Symfony generate these files dynamically in a
production environment is just too slow.
Instead, each time you use your application in the prod environment (and therefore, each time you
deploy), you should run the following command:
Listing 1-16
This will physically generate and write each file that you need (e.g. /js/abcd123.js). If you update
any of your assets, you'll need to run this again to regenerate the file.
1
2
3
# app/config/config_dev.yml
assetic:
use_controller: false
Next, since Symfony is no longer generating these assets for you, you'll need to dump them manually. To
do so, run the following command:
Listing 1-18
This physically writes all of the asset files you need for your dev environment. The big disadvantage is
that you need to run this each time you update an asset. Fortunately, by using the assetic:watch
command, assets will be regenerated automatically as they change:
Listing 1-19
The assetic:watch command was introduced in AsseticBundle 2.4. In prior versions, you had to use
the --watch option of the assetic:dump command for the same behavior.
Since running this command in the dev environment may generate a bunch of files, it's usually a good
idea to point your generated asset files to some isolated directory (e.g. /js/compiled), to keep things
organized:
Listing 1-20
1
2
3
Chapter 2
1
2
Chapter 2: Combining, Compiling and Minimizing Web Assets with PHP Libraries | 13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
web/assets/
css
main.css
code-highlight.css
js
bootstrap.js
jquery.js
main.js
scss
bootstrap
_alerts.scss
...
_variables.scss
_wells.scss
mixins
_alerts.scss
...
_vendor-prefixes.scss
bootstrap.scss
font-awesome
_animated.scss
...
_variables.scss
font-awesome.scss
1
2
3
4
5
6
# app/config/config.yml
assetic:
filters:
scssphp:
formatter: 'Leafo\ScssPhp\Formatter\Compressed'
# ...
The value of the formatter option is the fully qualified class name of the formatter used by the filter to
produce the compiled CSS file. Using the compressed formatter will minimize the resulting file, regardless
of whether the original files are regular CSS files or SCSS files.
Next, update your Twig template to add the {% stylesheets %} tag defined by Assetic:
Listing 2-4
1
2
3
4
5
6
7
8
9
10
11
12
13
{# app/Resources/views/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
<!-- ... -->
{% stylesheets filter="scssphp" output="css/app.css"
"assets/scss/bootstrap.scss"
"assets/scss/font-awesome.scss"
"assets/css/*.css"
%}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
This simple configuration compiles, combines and minifies the SCSS files into a regular CSS file that's put
in web/css/app.css. This is the only CSS file which will be served to your visitors.
Chapter 2: Combining, Compiling and Minimizing Web Assets with PHP Libraries | 14
1
2
3
4
5
# app/config/config.yml
assetic:
filters:
jsqueeze: ~
# ...
Next, update the code of your Twig template to add the {% javascripts %} tag defined by Assetic:
Listing 2-6
1
2
3
4
5
6
7
8
9
10
11
12
This simple configuration combines all the JavaScript files, minimizes the contents and saves the output
in the web/js/app.js file, which is the one that is served to your visitors.
The leading ? character in the jsqueeze filter name tells Assetic to only apply the filter when not in
debug mode. In practice, this means that you'll see unminified files while developing and minimized files
in the prod environment.
Chapter 2: Combining, Compiling and Minimizing Web Assets with PHP Libraries | 15
Chapter 3
Install UglifyJS
UglifyJS is available as a Node.js3 module. First, you need to install Node.js4 and then, decide the
installation method: global or local.
Global Installation
The global installation method makes all your projects use the very same UglifyJS version, which
simplifies its maintenance. Open your command console and execute the following command (you may
need to run it as a root user):
Listing 3-1
Now you can execute the global uglifyjs command anywhere on your system:
Listing 3-2
$ uglifyjs --help
1. https://github.com/mishoo/UglifyJS
2. https://github.com/fmarcia/UglifyCSS
3. https://nodejs.org/
4. https://nodejs.org/
Local Installation
It's also possible to install UglifyJS inside your project only, which is useful when your project requires
a specific UglifyJS version. To do this, install it without the -g option and specify the path where to put
the module:
Listing 3-3
1
2
$ cd /path/to/your/symfony/project
$ npm install uglify-js --prefix app/Resources
It is recommended that you install UglifyJS in your app/Resources folder and add the node_modules
folder to version control. Alternatively, you can create an npm package.json5 file and specify your
dependencies there.
Now you can execute the uglifyjs command that lives in the node_modules directory:
Listing 3-4
$ "./app/Resources/node_modules/.bin/uglifyjs" --help
1
2
3
4
5
6
# app/config/config.yml
assetic:
filters:
uglifyjs2:
# the path to the uglifyjs executable
bin: /usr/local/bin/uglifyjs
The path where UglifyJS is installed may vary depending on your system. To find out where npm
stores the bin folder, execute the following command:
Listing 3-6
$ npm bin -g
It should output a folder on your system, inside which you should find the UglifyJS executable.
If you installed UglifyJS locally, you can find the bin folder inside the node_modules folder. It's
called .bin in this case.
1
2
3
4
5
6
# app/config/config.yml
assetic:
# the path to the node executable
node: /usr/bin/nodejs
filters:
uglifyjs2:
5. http://browsenpm.org/package.json
7
8
1
2
3
The above example assumes that you have a bundle called AppBundle and your JavaScript files
are in the Resources/public/js directory under your bundle. However you can include your
JavaScript files no matter where they are.
With the addition of the uglifyjs2 filter to the asset tags above, you should now see minified
JavaScripts coming over the wire much faster.
1
2
3
To try this out, switch to your prod environment (app.php). But before you do, don't forget to clear
your cache and dump your assetic assets.
Instead of adding the filters to the asset tags, you can also configure which filters to apply for each
file in your application configuration file. See Filtering Based on a File Extension for more details.
1
2
3
4
5
6
# global installation
$ npm install -g uglifycss
# local installation
$ cd /path/to/your/symfony/project
$ npm install uglifycss --prefix app/Resources
1
2
3
4
5
# app/config/config.yml
assetic:
filters:
uglifycss:
bin: /usr/local/bin/uglifycss
To use the filter for your CSS files, add the filter to the Assetic stylesheets helper:
Listing 3-12
1
2
3
Just like with the uglifyjs2 filter, if you prefix the filter name with ? (i.e. ?uglifycss), the
minification will only happen when you're not in debug mode.
Chapter 4
The YUI Compressor is no longer maintained by Yahoo1. That's why you are strongly advised to
avoid using YUI utilities unless strictly necessary. Read How to Minify CSS/JS Files (Using UglifyJS
and UglifyCSS) for a modern and up-to-date alternative.
Yahoo! provides an excellent utility for minifying JavaScripts and stylesheets so they travel over the wire
faster, the YUI Compressor2. Thanks to Assetic, you can take advantage of this tool very easily.
1
2
3
4
5
6
7
8
# app/config/config.yml
assetic:
# java: '/usr/bin/java'
filters:
yui_css:
jar: '%kernel.root_dir%/Resources/java/yuicompressor.jar'
yui_js:
jar: '%kernel.root_dir%/Resources/java/yuicompressor.jar'
1. http://yuiblog.com/blog/2013/01/24/yui-compressor-has-a-new-owner/
2. http://yui.github.io/yuicompressor/
3. https://github.com/yui/yuicompressor/releases
Windows users need to remember to update config to proper Java location. In Windows7 x64 bit by
default it's C:\Program Files (x86)\Java\jre6\bin\java.exe.
You now have access to two new Assetic filters in your application: yui_css and yui_js. These will
use the YUI Compressor to minify stylesheets and JavaScripts, respectively.
1
2
3
The above example assumes that you have a bundle called AppBundle and your JavaScript files are
in the Resources/public/js directory under your bundle. This isn't important however - you
can include your JavaScript files no matter where they are.
With the addition of the yui_js filter to the asset tags above, you should now see minified JavaScripts
coming over the wire much faster. The same process can be repeated to minify your stylesheets.
Listing 4-3
1
2
3
1
2
3
Instead of adding the filter to the asset tags, you can also globally enable it by adding the apply_to
attribute to the filter configuration, for example in the yui_js filter apply_to: "\.js$". To
only have the filter applied in production, add this to the config_prod file rather than the common
config file. For details on applying filters by file extension, see Filtering Based on a File Extension.
Chapter 5
Using Jpegoptim
Jpegoptim1 is a utility for optimizing JPEG files. To use it with Assetic, make sure to have it already
installed on your system and then, configure its location using the bin option of the jpegoptim filter:
Listing 5-1
1
2
3
4
5
# app/config/config.yml
assetic:
filters:
jpegoptim:
bin: path/to/jpegoptim
1
2
3
4
{% image '@AppBundle/Resources/public/images/example.jpg'
filter='jpegoptim' output='/images/example.jpg' %}
<img src="{{ asset_url }}" alt="Example"/>
{% endimage %}
1. http://www.kokkonen.net/tjko/projects.html
Chapter 5: How to Use Assetic for Image Optimization with Twig Functions | 22
1
2
3
4
5
6
# app/config/config.yml
assetic:
filters:
jpegoptim:
bin: path/to/jpegoptim
strip_all: true
1
2
3
4
5
6
# app/config/config.yml
assetic:
filters:
jpegoptim:
bin: path/to/jpegoptim
max: 70
1
2
3
4
5
6
7
8
# app/config/config.yml
assetic:
filters:
jpegoptim:
bin: path/to/jpegoptim
twig:
functions:
jpegoptim: ~
You can also specify the output directory for images in the Assetic configuration file:
Listing 5-7
1
2
3
4
5
6
7
8
# app/config/config.yml
assetic:
filters:
jpegoptim:
bin: path/to/jpegoptim
twig:
functions:
jpegoptim: { output: images/*.jpg }
For uploaded images, you can compress and manipulate them using the LiipImagineBundle2
community bundle.
2. http://knpbundles.com/liip/LiipImagineBundle
Chapter 5: How to Use Assetic for Image Optimization with Twig Functions | 23
Chapter 6
1
2
3
4
5
6
7
# app/config/config.yml
assetic:
filters:
coffee:
bin:
/usr/bin/coffee
node:
/usr/bin/node
node_paths: [/usr/lib/node_modules/]
1
2
3
This is all that's needed to compile this CoffeeScript file and serve it as the compiled JavaScript.
1
2
3
4
5
{% javascripts '@AppBundle/Resources/public/js/example.coffee'
'@AppBundle/Resources/public/js/another.coffee'
filter='coffee' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
Both files will now be served up as a single file compiled into regular JavaScript.
1
2
3
4
5
6
7
8
# app/config/config.yml
assetic:
filters:
coffee:
bin:
node:
node_paths:
apply_to:
/usr/bin/coffee
/usr/bin/node
[/usr/lib/node_modules/]
'\.coffee$'
With this option, you no longer need to specify the coffee filter in the template. You can also list
regular JavaScript files, all of which will be combined and rendered as a single JavaScript file (with only
the .coffee files being run through the CoffeeScript filter):
Listing 6-5
1
2
3
4
5
{% javascripts '@AppBundle/Resources/public/js/example.coffee'
'@AppBundle/Resources/public/js/another.coffee'
'@AppBundle/Resources/public/js/regular.js' %}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
Chapter 7
1. https://getcomposer.org/doc/00-intro.md
2. https://github.com/FriendsOfSymfony/FOSUserBundle
3. https://packagist.org
4. http://knpbundles.com/
This will choose the best version for your project, add it to composer.json and download its code into
the vendor/ directory. If you need a specific version, include it as the second argument of the composer
require5 command:
Listing 7-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
// ...
public function registerBundles()
{
$bundles = array(
// ...
new FOS\UserBundle\FOSUserBundle(),
);
// ...
}
}
In a few rare cases, you may want a bundle to be only enabled in the development environment. For
example, the DoctrineFixturesBundle helps to load dummy data - something you probably only want to
do while developing. To only load this bundle in the dev and test environments, register the bundle in
this way:
Listing 7-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
// ...
public function registerBundles()
{
$bundles = array(
// ...
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
}
// ...
}
}
5. https://getcomposer.org/doc/03-cli.md#require
Instead of the full bundle name, you can also pass the short name used as the root of the bundle's
configuration:
Listing 7-6
1
2
3
4
5
6
7
8
9
10
11
assetic:
debug:
use_controller:
enabled:
profiler:
read_from:
write_to:
java:
node:
node_paths:
# ...
'%kernel.debug%'
'%kernel.debug%'
false
'%kernel.root_dir%/../web'
'%assetic.read_from%'
/usr/bin/java
/usr/local/bin/node
[]
Other Setup
At this point, check the README file of your brand new bundle to see what to do next. Have fun!
Chapter 8
Bundle Name
A bundle is also a PHP namespace. The namespace must follow the PSR-01 or PSR-42 interoperability
standards for PHP namespaces and class names: it starts with a vendor segment, followed by zero or more
category segments, and it ends with the namespace short name, which must end with a Bundle suffix.
A namespace becomes a bundle as soon as you add a bundle class to it. The bundle class name must
follow these simple rules:
1. http://www.php-fig.org/psr/psr-0/
2. http://www.php-fig.org/psr/psr-4/
Namespace
Acme\Bundle\BlogBundle
AcmeBlogBundle
Acme\BlogBundle
AcmeBlogBundle
By convention, the getName() method of the bundle class should return the class name.
If you share your bundle publicly, you must use the bundle class name as the name of the repository
(AcmeBlogBundle and not BlogBundle for instance).
Symfony core Bundles do not prefix the Bundle class with Symfony and always add a Bundle subnamespace; for example: FrameworkBundle3.
Each bundle has an alias, which is the lower-cased short version of the bundle name using underscores
(acme_blog for AcmeBlogBundle). This alias is used to enforce uniqueness within a project and for
defining bundle's configuration options (see below for some usage examples).
Directory Structure
The basic directory structure of an AcmeBlogBundle must read as follows:
Listing 8-1
1
2
3
4
5
6
7
8
9
10
11
12
13
<your-bundle>/
AcmeBlogBundle.php
Controller/
README.md
LICENSE
Resources/
config/
doc/
index.rst
translations/
views/
public/
Tests/
The following files are mandatory, because they ensure a structure convention that automated tools
can rely on:
AcmeBlogBundle.php:
This is the class that transforms a plain directory into a Symfony bundle (change
this to your bundle's name);
README.md: This file contains the basic description of the bundle and it usually shows some basic
examples and links to its full documentation (it can use any of the markup formats supported by
GitHub, such as README.rst);
LICENSE: The full contents of the license used by the code. Most third-party bundles are published
under the MIT license, but you can choose any license4;
Resources/doc/index.rst: The root file for the Bundle documentation.
The depth of sub-directories should be kept to the minimum for most used classes and files (two levels
maximum).
3. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/FrameworkBundle.html
4. http://choosealicense.com/
The bundle directory is read-only. If you need to write temporary files, store them under the cache/
or log/ directory of the host application. Tools can generate files in the bundle directory structure, but
only if the generated files are going to be part of the repository.
The following classes and files have specific emplacements (some are mandatory and others are just
conventions followed by most developers):
Type
Directory
Mandatory?
Commands
Command/
Yes
Controllers
Controller/
No
DependencyInjection/
Yes
Event Listeners
EventListener/
No
Model/
No
Configuration
Resources/config/
No
Resources/public/
Yes
Translation files
Resources/translations/
Yes
Templates
Resources/views/
Yes
Tests/
No
[1] See How to Provide Model Classes for several Doctrine Implementations for how to handle the mapping
with a compiler pass.
Classes
The
bundle
directory
structure
is
used
as
the
namespace
ContentController
controller
is
stored
in
ContentController.php
and
the
fully
Acme\BlogBundle\Controller\ContentController.
hierarchy.
For
instance,
Acme/BlogBundle/Controller/
qualified
class
name
is
All classes and files must follow the Symfony coding standards.
Some classes should be seen as facades and should be as short as possible, like Commands, Helpers,
Listeners and Controllers.
Classes that connect to the event dispatcher should be suffixed with Listener.
Exception classes should be stored in an Exception sub-namespace.
Vendors
A bundle must not embed third-party PHP libraries. It should rely on the standard Symfony autoloading
instead.
A bundle should not embed third-party libraries written in JavaScript, CSS or any other language.
Tests
A bundle should come with a test suite written with PHPUnit and stored under the Tests/ directory.
Tests should follow the following principles:
PDF brought to you by
generated on July 28, 2016
The test suite must be executable with a simple phpunit command run from a sample application;
The functional tests should only be used to test the response output and some profiling information
if you have some;
The tests should cover at least 95% of the code base.
A test suite must not contain AllTests.php scripts, but must rely on the existence of a
phpunit.xml.dist file.
Documentation
All classes and functions must come with full PHPDoc.
Extensive documentation should also be provided in the reStructuredText format, under the
Resources/doc/ directory; the Resources/doc/index.rst file is the only mandatory file and
must be the entry point for the documentation.
Installation Instructions
In order to ease the installation of third-party bundles, consider using the following standardized
instructions in your README.md file.
Listing 8-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Installation
============
Step 1: Download the Bundle
--------------------------Open a command console, enter your project directory and execute the
following command to download the latest stable version of this bundle:
```bash
$ composer require <package-name> "~1"
```
This command requires you to have Composer installed globally, as explained
in the [installation chapter](https://getcomposer.org/doc/00-intro.md)
of the Composer documentation.
Step 2: Enable the Bundle
------------------------Then, enable the bundle by adding it to the list of registered bundles
in the `app/AppKernel.php` file of your project:
```php
<?php
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new <vendor>\<bundle-name>\<bundle-long-name>(),
);
// ...
}
42
43
44
// ...
}
```
The example above assumes that you are installing the latest stable version of the bundle, where you don't
have to provide the package version number (e.g. composer require friendsofsymfony/userbundle). If the installation instructions refer to some past bundle version or to some unstable version,
include the version constraint (e.g. composer require friendsofsymfony/user-bundle
"~2.0@dev").
Optionally, you can add more installation steps (Step 3, Step 4, etc.) to explain other required installation
tasks, such as registering routes or dumping assets.
Routing
If the bundle provides routes, they must be prefixed with the bundle alias. For example, if your bundle is
called AcmeBlogBundle, all its routes must be prefixed with acme_blog_.
Templates
If a bundle provides templates, they must use Twig. A bundle must not provide a main layout, except if
it provides a full working application.
Translation Files
If a bundle provides message translations, they must be defined in the XLIFF format; the domain should
be named after the bundle name (acme_blog).
A bundle must not override existing messages from another bundle.
Configuration
To provide more flexibility, a bundle can provide configurable settings by using the Symfony built-in
mechanisms.
For simple configuration settings, rely on the default parameters entry of the Symfony configuration.
Symfony parameters are simple key/value pairs; a value being any valid PHP value. Each parameter name
should start with the bundle alias, though this is just a best-practice suggestion. The rest of the parameter
name will use a period (.) to separate different parts (e.g. acme_blog.author.email).
The end user can provide values in any configuration file:
Listing 8-3
1
2
3
# app/config/config.yml
parameters:
acme_blog.author.email: '[email protected]'
$container->getParameter('acme_blog.author.email');
Even if this mechanism is simple enough, you should consider using the more advanced semantic bundle
configuration.
PDF brought to you by
generated on July 28, 2016
Versioning
Bundles must be versioned following the Semantic Versioning Standard5.
Services
If the bundle defines services, they must be prefixed with the bundle alias. For example, AcmeBlogBundle
services must be prefixed with acme_blog.
In addition, services not meant to be used by the application directly, should be defined as private.
You can learn much more about service loading in bundles reading this article: How to Load Service
Configuration inside a Bundle.
Composer Metadata
The composer.json file should include at least the following metadata:
name
Consists of the vendor and the short bundle name. If you are releasing the bundle on your own
instead of on behalf of a company, use your personal name (e.g. johnsmith/blog-bundle). The bundle
short name excludes the vendor name and separates each word with an hyphen. For example:
AcmeBlogBundle is transformed into blog-bundle and AcmeSocialConnectBundle is transformed into socialconnect-bundle.
description
is the preferred license for Symfony bundles, but you can use any other license.
autoload
This information is used by Symfony to load the classes of the bundle. The PSR-46 autoload
standard is recommended for modern bundles, but PSR-07 standard is also supported.
In order to make it easier for developers to find your bundle, register it on Packagist8, the official
repository for Composer packages.
5. http://semver.org/
6. http://www.php-fig.org/psr/psr-4/
7. http://www.php-fig.org/psr/psr-0/
8. https://packagist.org/
2.5-BC: the new 2.5 API with a backwards-compatible layer so that the 2.4 API still works. This is
only available in PHP 5.3.9+.
Starting with Symfony 2.7, the support for the 2.4 API has been dropped and the minimal PHP
version required for Symfony was increased to 5.3.9. If your bundles requires Symfony >=2.7, you
don't need to take care about the 2.4 API anymore.
As a bundle author, you'll want to support both API's, since some users may still be using the 2.4 API.
Specifically, if your bundle adds a violation directly to the ExecutionContext9 (e.g. like in a custom
validation constraint), you'll need to check for which API is being used. The following code, would work
for all users:
Listing 8-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
// ...
class ContainsAlphanumericValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if ($this->context instanceof ExecutionContextInterface) {
// the 2.5 API
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation()
;
} else {
// the 2.4 API
$this->context->addViolation(
$constraint->message,
array('%string%' => $value)
);
}
}
}
9. http://api.symfony.com/2.7/Symfony/Component/Validator/Context/ExecutionContext.html
Chapter 9
1
2
3
4
5
6
7
8
9
10
11
12
// src/UserBundle/UserBundle.php
namespace UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class UserBundle extends Bundle
{
public function getParent()
{
return 'FOSUserBundle';
}
}
By making this simple change, you can now override several parts of the FOSUserBundle simply by
creating a file with the same name.
Despite the method name, there is no parent/child relationship between the bundles, it is just a way
to extend and override an existing bundle.
1. https://github.com/friendsofsymfony/fosuserbundle
Overriding Controllers
add some functionality to the registerAction of a
RegistrationController that lives inside FOSUserBundle. To do so, just create your own
RegistrationController.php file, override the bundle's original method, and change its
functionality:
Suppose
Listing 9-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
you
want
to
// src/UserBundle/Controller/RegistrationController.php
namespace UserBundle\Controller;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
class RegistrationController extends BaseController
{
public function registerAction()
{
$response = parent::registerAction();
Depending
on
how
severely
might
call
Overriding controllers in this way only works if the bundle refers to the controller using the standard
FOSUserBundle:Registration:register syntax in routes and templates. This is the best
practice.
Chapter 10
Templates
For information on overriding templates, see
Overriding Bundle Templates.
How to Use Bundle Inheritance to Override Parts of a Bundle
Routing
Routing is never automatically imported in Symfony. If you want to include the routes from any
bundle, then they must be manually imported from somewhere in your application (e.g. app/config/
routing.yml).
The easiest way to "override" a bundle's routing is to never import it at all. Instead of importing a
third-party bundle's routing, simply copy that routing file into your application, modify it, and import it
instead.
Controllers
Assuming the third-party bundle involved uses non-service controllers (which is almost always the case),
you can easily override controllers via bundle inheritance. For more information, see How to Use Bundle
Inheritance to Override Parts of a Bundle. If the controller is a service, see the next section on how to
override it.
1
2
3
# app/config/config.yml
parameters:
translator.class: Acme\HelloBundle\Translation\Translator
Secondly, if the class is not available as a parameter, you want to make sure the class is always overridden
when your bundle is used or if you need to modify something beyond just the class name, you should use
a compiler pass:
Listing 10-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/Acme/DemoBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
namespace Acme\DemoBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class OverrideServiceCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('original-service-id');
$definition->setClass('Acme\DemoBundle\YourService');
}
}
In this example you fetch the service definition of the original service, and set its class name to your own
class.
See How to Work with Compiler Passes in Bundles for information on how to use compiler passes. If you
want to do something beyond just overriding the class, like adding a method call, you can only use the
compiler pass method.
Forms
In order to override a form type, it has to be registered as a service (meaning it is tagged as form.type).
You can then override it as you would override any service as explained in Services & Configuration.
This, of course, will only work if the type is referred to by its alias rather than being instantiated, e.g.:
Listing 10-3
$builder->add('name', 'custom_type');
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#overrides
rather than:
Listing 10-4
Validation Metadata
Symfony loads all validation configuration files from every bundle and combines them into one validation
metadata tree. This means you are able to add new constraints to a property, but you cannot override
them.
To override this, the 3rd party bundle needs to have configuration for validation groups. For instance,
the FOSUserBundle has this configuration. To create your own validation, add the constraints to a new
validation group:
Listing 10-5
1
2
3
4
5
6
7
8
9
10
# src/Acme/UserBundle/Resources/config/validation.yml
FOS\UserBundle\Model\User:
properties:
plainPassword:
- NotBlank:
groups: [AcmeValidation]
- Length:
min: 6
minMessage: fos_user.password.short
groups: [AcmeValidation]
Now, update the FOSUserBundle configuration, so it uses your validation groups instead of the original
ones.
Translations
Translations are not related to bundles, but to domains. That means that you can override the
translations from any translation file, as long as it is in the correct domain.
The last translation file always wins. That means that you need to make sure that the bundle
containing your translations is loaded after any bundle whose translations you're overriding. This is
done in AppKernel.
Translation files are also not aware of bundle inheritance. If you want to override translations
from the parent bundle, be sure that the parent bundle is loaded before the child bundle in the
AppKernel class.
The file that always wins is the one that is placed in app/Resources/translations, as those
files are always loaded last.
Chapter 11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(...);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
// comment or remove this line:
// $bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
// ...
}
}
}
dump($this->container->get('kernel')->getBundle('AcmeDemoBundle')->getPath());
die();
Some bundles rely on other bundles, if you remove one of the two, the other will probably not work. Be
sure that no other bundles, third party or self-made, rely on the bundle you are about to remove.
1. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Bundle/BundleInterface.html#method_getPath
If one bundle relies on another, in most cases it means that it uses some services from the bundle.
Searching for the bundle alias string may help you spot them (e.g. acme_demo for bundles
depending on AcmeDemoBundle).
If a third party bundle relies on another bundle, you can find that bundle mentioned in the
composer.json file included in the bundle directory.
Chapter 12
1
2
3
4
5
6
7
8
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
namespace Acme\HelloBundle\DependencyInjection;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class AcmeHelloExtension extends Extension
{
1. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Extension/ExtensionInterface.html
2. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Extension/Extension.html
9
10
11
12
13
1
2
3
4
5
6
7
8
9
10
// ...
use Acme\HelloBundle\DependencyInjection\UnconventionalExtensionClass;
class AcmeHelloBundle extends Bundle
{
public function getContainerExtension()
{
return new UnconventionalExtensionClass();
}
}
Since the new Extension class name doesn't follow the naming conventions, you should also override
Extension::getAlias()4 to return the correct DI alias. The DI alias is the name used to refer
to the bundle in the container (e.g. in the app/config/config.yml file). By default, this is done
by removing the Extension suffix and converting the class name to underscores (e.g.
AcmeHelloExtension's DI alias is acme_hello).
1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
// ...
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader(
$container,
new FileLocator(__DIR__.'/../Resources/config')
);
$loader->load('services.xml');
}
3. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Bundle/Bundle.html#method_build
4. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Extension/Extension.html#method_getAlias
If you removed the default file with service definitions (i.e. app/config/services.yml), make
sure to also remove it from the imports key in app/config/config.yml.
1
2
3
4
5
6
7
8
9
10
11
// ...
public function load(array $configs, ContainerBuilder $container)
{
// ...
$this->addClassesToCompile(array(
'AppBundle\\Manager\\UserManager',
'AppBundle\\Utils\\Slugger',
// ...
));
}
If some class extends from other classes, all its parents are automatically included in the list of classes
to compile.
Chapter 13
1
2
framework:
form: true
Listing 13-2
1
2
3
4
5
# app/config/config.yml
acme_social:
twitter:
client_id: 123
client_secret: your_secret
Read more about the extension in How to Load Service Configuration inside a Bundle.
If a bundle provides an Extension class, then you should not generally override any service container
parameters from that bundle. The idea is that if an Extension class is present, every setting that
should be configurable should be present in the configuration made available by that class. In
other words, the extension class defines all the public configuration settings for which backward
compatibility will be maintained.
For parameter handling within a dependency injection container see Using Parameters within a Dependency
Injection Class.
1
2
3
4
5
6
7
8
array(
array(
'twitter' => array(
'client_id' => 123,
'client_secret' => 'your_secret',
),
),
)
Notice that this is an array of arrays, not just a single flat array of the configuration values. This is
intentional, as it allows Symfony to parse several configuration resources. For example, if acme_social
appears in another configuration file - say config_dev.yml - with different values beneath it, the
incoming array might look like this:
Listing 13-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
array(
// values from config.yml
array(
'twitter' => array(
'client_id' => 123,
'client_secret' => 'your_secret',
),
),
// values from config_dev.yml
array(
'twitter' => array(
'client_id' => 456,
),
),
)
The order of the two arrays depends on which one is set first.
But don't worry! Symfony's Config component will help you merge these values, provide defaults and give
the user validation errors on bad configuration. Here's how it works. Create a Configuration class
in the DependencyInjection directory and build a tree that defines the structure of your bundle's
configuration.
The Configuration class to handle the sample configuration looks like:
Listing 13-5
// src/Acme/SocialBundle/DependencyInjection/Configuration.php
namespace Acme\SocialBundle\DependencyInjection;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('acme_social');
$rootNode
->children()
->arrayNode('twitter')
->children()
->integerNode('client_id')->end()
->scalarNode('client_secret')->end()
->end()
->end() // twitter
->end()
;
return $treeBuilder;
}
}
The Configuration class can be much more complicated than shown here, supporting "prototype" nodes,
advanced validation, XML-specific normalization and advanced merging. You can read more about this in
the Config component documentation. You can also see it in action by checking out some core Configuration
classes, such as the one from the FrameworkBundle Configuration1 or the TwigBundle Configuration2.
This class can now be used in your load() method to merge configurations and force validation (e.g. if
an additional option was passed, an exception will be thrown):
Listing 13-6
1
2
3
4
5
6
7
The processConfiguration() method uses the configuration tree you've defined in the
Configuration class to validate, normalize and merge all the configuration arrays together.
1. https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php
2. https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php
Instead of calling processConfiguration() in your extension each time you provide some
configuration options, you might want to use the ConfigurableExtension3 to do this
automatically for you:
Listing 13-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
namespace Acme\HelloBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
class AcmeHelloExtension extends ConfigurableExtension
{
// note that this method is called loadInternal and not load
protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
{
// ...
}
}
This class uses the getConfiguration() method to get the Configuration instance. You should
override it if your Configuration class is not called Configuration or if it is not placed in the same
namespace as the extension.
1
2
3
4
5
6
7
8
9
10
3. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/DependencyInjection/ConfigurableExtension.html
4. http://php.net/manual/en/function.isset.php
Supporting XML
Symfony allows people to provide the configuration in three different formats: Yaml, XML and PHP.
Both Yaml and PHP use the same syntax and are supported by default when using the Config component.
Supporting XML requires you to do some more things. But when sharing your bundle with others, it is
recommended that you follow these steps.
1
2
3
4
5
6
7
8
9
10
11
12
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
// ...
class AcmeHelloExtension extends Extension
{
// ...
public function getNamespace()
{
return 'http://acme_company.com/schema/dic/hello';
}
}
By convention, the XSD file lives in the Resources/config/schema, but you can place it anywhere
you like. You should return this path as the base path:
Listing 13-10
1
2
3
4
5
6
7
8
9
10
11
12
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
// ...
class AcmeHelloExtension extends Extension
{
// ...
public function getXsdValidationBasePath()
{
return __DIR__.'/../Resources/config/schema';
}
}
Listing 13-11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
location
will
be
Chapter 14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
namespace Acme\HelloBundle\DependencyInjection;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class AcmeHelloExtension extends Extension implements PrependExtensionInterface
{
// ...
public function prepend(ContainerBuilder $container)
{
// ...
}
}
1. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Extension/PrependExtensionInterface.html
Inside the prepend()2 method, developers have full access to the ContainerBuilder3 instance just
before the load()4 method is called on each of the registered bundle Extensions. In order to prepend
settings to a bundle extension developers can use the prependExtensionConfig()5 method on the
ContainerBuilder6 instance. As this method only prepends settings, any other settings done explicitly
inside the app/config/config.yml would override these prepended settings.
The following example illustrates how to prepend a configuration setting in multiple bundles as well as
disable a flag in multiple bundles in case a specific other bundle is not registered:
Listing 14-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
The above would be the equivalent of writing the following into the app/config/config.yml in case
AcmeGoodbyeBundle is not registered and the entity_manager_name setting for acme_hello is set
to non_default:
Listing 14-3
1
2
3
4
5
6
7
8
9
# app/config/config.yml
acme_something:
# ...
use_acme_goodbye: false
entity_manager_name: non_default
acme_other:
# ...
use_acme_goodbye: false
2. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Extension/PrependExtensionInterface.html#method_prepend
3. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/ContainerBuilder.html
4. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Extension/ExtensionInterface.html#method_load
5. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/ContainerBuilder.html#method_prependExtensionConfig
6. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/ContainerBuilder.html
Chapter 15
1
2
3
sub vcl_recv {
remove req.http.Forwarded;
}
If you do not have access to your Varnish configuration, you can instead configure Symfony to distrust
the Forwarded header as detailed in the cookbook.
another proxy (as Varnish does not do HTTPS itself) on the default HTTPS port 443 that handles the
SSL termination and forwards the requests as HTTP requests to Varnish with an X-Forwarded-Proto
header. In this case, you need to add the following configuration snippet:
Listing 15-2
1
2
3
4
5
6
7
sub vcl_recv {
if (req.http.X-Forwarded-Proto == "https" ) {
set req.http.X-Forwarded-Port = "443";
} else {
set req.http.X-Forwarded-Port = "80";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sub vcl_recv {
// Remove all cookies except the session ID.
if (req.http.Cookie) {
set req.http.Cookie = ";" + req.http.Cookie;
set req.http.Cookie = regsuball(req.http.Cookie,
set req.http.Cookie = regsuball(req.http.Cookie,
set req.http.Cookie = regsuball(req.http.Cookie,
set req.http.Cookie = regsuball(req.http.Cookie,
if (req.http.Cookie == "") {
// If there are no more cookies, remove the header to get page cached.
unset req.http.Cookie;
}
}
}
If content is not different for every user, but depends on the roles of a user, a solution is to separate
the cache per group. This pattern is implemented and explained by the FOSHttpCacheBundle3 under
the name User Context4.
2. https://www.varnish-cache.org/trac/wiki/VCLExampleRemovingSomeCookies
3. http://foshttpcachebundle.readthedocs.org/
4. http://foshttpcachebundle.readthedocs.org/en/latest/features/user-context.html
1
2
3
4
5
6
7
8
9
10
11
sub vcl_fetch {
/* By default, Varnish3 ignores Cache-Control: no-cache and private
https://www.varnish-cache.org/docs/3.0/tutorial/increasing_your_hitrate.html#cache-control
*/
if (beresp.http.Cache-Control ~ "private" ||
beresp.http.Cache-Control ~ "no-cache" ||
beresp.http.Cache-Control ~ "no-store"
) {
return (hit_for_pass);
}
}
You can see the default behavior of Varnish in the form of a VCL file: default.vcl5 for Varnish 3,
builtin.vcl6 for Varnish 4.
First, configure Varnish so that it advertises its ESI support by adding a Surrogate-Capability
header to requests forwarded to the backend application:
Listing 15-5
1
2
3
4
sub vcl_recv {
// Add a Surrogate-Capability header to announce ESI support.
set req.http.Surrogate-Capability = "abc=ESI/1.0";
}
The abc part of the header isn't important unless you have multiple "surrogates" that need to
advertise their capabilities. See Surrogate-Capability Header8 for details.
Then, optimize Varnish so that it only parses the response contents when there is at least one ESI tag by
checking the Surrogate-Control header that Symfony adds automatically:
Listing 15-6
1
2
sub vcl_backend_response {
// Check for ESI acknowledgement and remove Surrogate-Control header
5. https://github.com/varnish/Varnish-Cache/blob/3.0/bin/varnishd/default.vcl
6. https://github.com/varnish/Varnish-Cache/blob/4.1/bin/varnishd/builtin.vcl
7. http://www.w3.org/TR/edge-arch
8. http://www.w3.org/TR/edge-arch
3
4
5
6
7
if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
unset beresp.http.Surrogate-Control;
set beresp.do_esi = true;
}
}
If you followed the advice about ensuring a consistent caching behavior, those VCL functions already
exist. Just append the code to the end of the function, they won't interfere with each other.
Cache Invalidation
If you want to cache content that changes frequently and still serve the most recent version to users, you
need to invalidate that content. While cache invalidation9 allows you to purge content from your proxy
before it has expired, it adds complexity to your caching setup.
The open source FOSHttpCacheBundle10 takes the pain out of cache invalidation by helping you to
organize your caching and invalidation setup.
The documentation of the FOSHttpCacheBundle11 explains how to configure Varnish and other
reverse proxies for cache invalidation.
9. http://tools.ietf.org/html/rfc2616#section-13.10
10. http://foshttpcachebundle.readthedocs.org/
11. http://foshttpcachebundle.readthedocs.org/
Chapter 16
How to Cache Most of the Page and still be able to Use CSRF Protection
To cache a page that contains a CSRF token, you can use more advanced caching techniques like ESI
fragments, where you cache the full page and embedding the form inside an ESI tag with no cache at all.
Another option would be to load the form via an uncached AJAX request, but cache the rest of the HTML
response.
Or you can even load just the CSRF token with an AJAX request and replace the form field value with it.
Chapter 17
Installing Composer
Composer1 is the package manager used by modern PHP applications. Use Composer to manage
dependencies in your Symfony applications and to install Symfony Components in your PHP projects.
It's recommended to install Composer globally in your system as explained in the following sections.
Learn more
Read the Composer documentation4 to learn more about its usage and features.
1. https://getcomposer.org/
2. https://getcomposer.org/download
3. https://getcomposer.org/Composer-Setup.exe
4. https://getcomposer.org/doc/00-intro.md
Chapter 18
1
2
3
4
5
6
7
8
9
10
11
12
13
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
// ...
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
As you can see, when Symfony is loaded, it uses the given environment to determine which configuration
file to load. This accomplishes the goal of multiple environments in an elegant, powerful and transparent
way.
Of course, in reality, each environment differs only somewhat from others. Generally, all environments
will share a large base of common configuration. Opening the config_dev.yml configuration file, you
can see how this is accomplished easily and transparently:
Listing 18-2
1
2
3
4
imports:
- { resource: config.yml }
# ...
To share common configuration, each environment's configuration file simply first imports from a
central configuration file (config.yml). The remainder of the file can then deviate from the default
configuration by overriding individual parameters. For example, by default, the web_profiler toolbar
is disabled. However, in the dev environment, the toolbar is activated by modifying the value of the
toolbar option in the config_dev.yml configuration file:
Listing 18-3
1
2
3
4
5
6
7
# app/config/config_dev.yml
imports:
- { resource: config.yml }
web_profiler:
toolbar: true
# ...
1
2
http://localhost/app.php
http://localhost/app_dev.php
The given URLs assume that your web server is configured to use the web/ directory of the
application as its root. Read more in Installing Symfony.
If you open up one of these files, you'll quickly see that the environment used by each is explicitly set:
Listing 18-5
1
2
3
4
5
6
// web/app.php
// ...
$kernel = new AppKernel('prod', false);
// ...
The prod key specifies that this application will run in the prod environment. A Symfony application
can be executed in any environment by using this code and changing the environment string.
The test environment is used when writing functional tests and is not accessible in the browser
directly via a front controller. In other words, unlike the other environments, there is no
app_test.php front controller file.
Debug Mode
Important, but unrelated to the topic of environments is the false argument as the second argument
to the AppKernel constructor. This specifies if the application should run in "debug mode".
Regardless of the environment, a Symfony application can be run with debug mode set to true or
false. This affects many things in the application, such as if errors should be displayed or if cache
files are dynamically rebuilt on each request. Though not a requirement, debug mode is generally set
to true for the dev and test environments and false for the prod environment.
Internally, the value of the debug mode becomes the kernel.debug parameter used inside the
service container. If you look inside the application configuration file, you'll see the parameter used,
for example, to turn logging on or off when using the Doctrine DBAL:
Listing 18-6
1
2
3
4
doctrine:
dbal:
logging: '%kernel.debug%'
# ...
As of Symfony 2.3, showing errors or not no longer depends on the debug mode. You'll need to
enable that in your front controller by calling enable()1.
1
2
3
4
5
6
7
8
In addition to the --env and --debug options, the behavior of Symfony commands can also be
controlled with environment variables. The Symfony console application checks the existence and value
of these environment variables before executing any command:
SYMFONY_ENV
Sets the execution environment of the command to the value of this variable (dev, prod, test, etc.);
SYMFONY_DEBUG
1. http://api.symfony.com/2.7/Symfony/Component/Debug/Debug.html#method_enable
Suppose, for example, that before deployment, you need to benchmark your application. One way
to benchmark the application is to use near-production settings, but with Symfony's web_profiler
enabled. This allows Symfony to record information about your application while benchmarking.
The best way to accomplish this is via a new environment called, for example, benchmark. Start by
creating a new configuration file:
Listing 18-8
1
2
3
4
5
6
# app/config/config_benchmark.yml
imports:
- { resource: config_prod.yml }
framework:
profiler: { only_exceptions: false }
Due to the way in which parameters are resolved, you cannot use them to build paths in imports
dynamically. This means that something like the following doesn't work:
Listing 18-9
1
2
3
# app/config/config.yml
imports:
- { resource: '%kernel.root_dir%/parameters.yml' }
And with this simple addition, the application now supports a new environment called benchmark.
This new configuration file imports the configuration from the prod environment and modifies it. This
guarantees that the new environment is identical to the prod environment, except for any changes
explicitly made here.
Because you'll want this environment to be accessible via a browser, you should also create a front
controller for it. Copy the web/app.php file to web/app_benchmark.php and edit the environment
to be benchmark:
Listing 18-10
1
2
3
4
5
6
7
// web/app_benchmark.php
// ...
// change just this line
$kernel = new AppKernel('benchmark', false);
// ...
http://localhost/app_benchmark.php
Some environments, like the dev environment, are never meant to be accessed on any deployed
server by the public. This is because certain environments, for debugging purposes, may give too
much information about the application or underlying infrastructure. To be sure these environments
aren't accessible, the front controller is usually protected from external IP addresses via the following
code at the top of the controller:
Listing 18-12
By default, these cached files are largely stored in the app/cache directory. However, each environment
caches its own set of files:
Listing 18-13
1
2
3
4
5
6
<your-project>/
app/
cache/
dev/
prod/
...
Sometimes, when debugging, it may be helpful to inspect a cached file to understand how something
is working. When doing so, remember to look in the directory of the environment you're using (most
commonly dev while developing and debugging). While it can vary, the app/cache/dev directory
includes the following:
appDevDebugProjectContainer.php
The cached "service container" that represents the cached application configuration.
appDevUrlGenerator.php
The PHP class generated from the routing configuration and used when generating URLs.
appDevUrlMatcher.php
The PHP class used for route matching - look here to see the compiled regular expression logic used
to match incoming URLs to different routes.
twig/
Going further
Read the article on How to Set external Parameters in the Service Container.
Chapter 19
1
2
3
4
5
6
7
8
9
10
11
12
13
your-project/
app/
cache/
config/
logs/
...
src/
...
vendor/
...
web/
app.php
...
1
2
3
4
5
6
7
8
9
10
11
12
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
// ...
public function getCacheDir()
{
return $this->rootDir.'/'.$this->environment.'/cache';
}
}
$this->rootDir is the absolute path to the app directory and $this->environment is the current
environment (i.e. dev). In this case you have changed the location of the cache directory to app/
{environment}/cache.
You should keep the cache directory different for each environment, otherwise some unexpected
behavior may happen. Each environment generates its own cached configuration files, and so each
needs its own directory to store those cache files.
// app/AppKernel.php
1
2
3
4
5
6
7
8
9
10
11
12
// ...
class AppKernel extends Kernel
{
// ...
public function getLogDir()
{
return $this->rootDir.'/'.$this->environment.'/logs';
}
}
require_once __DIR__.'/../Symfony/app/bootstrap.php.cache';
require_once __DIR__.'/../Symfony/app/AppKernel.php';
You also need to change the extra.symfony-web-dir option in the composer.json file:
Listing 19-5
1
2
3
4
5
6
7
{
...
"extra": {
...
"symfony-web-dir": "my_new_web_dir"
}
}
Some shared hosts have a public_html web directory root. Renaming your web directory from
web to public_html is one way to make your Symfony project work on your shared host. Another
way is to deploy your application to a directory outside of your web root, delete your public_html
directory, and then replace it with a symbolic link to the web in your project.
If you use the AsseticBundle, you need to configure the read_from option to point to the correct
web directory:
Listing 19-6
1
2
3
4
5
6
# app/config/config.yml
# ...
assetic:
# ...
read_from: '%kernel.root_dir%/../../public_html'
Now you just need to clear the cache and dump the assets again and your application should work:
Listing 19-7
1
2
1
2
3
4
5
6
{
"config": {
"bin-dir": "bin",
"vendor-dir": "/some/dir/vendor"
},
}
// app/autoload.php
// ...
$loader = require '/some/dir/vendor/autoload.php';
This modification can be of interest if you are working in a virtual environment and cannot use NFS
- for example, if you're running a Symfony application using Vagrant/VirtualBox in a guest operating
system.
Chapter 20
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
my_bundle:
logging: true
# true, as expected
my_bundle:
logging: '%kernel.debug%'
# true/false (depends on 2nd parameter of AppKernel),
# as expected, because %kernel.debug% inside configuration
# gets evaluated before being passed to the extension
my_bundle: ~
# passes the string "%kernel.debug%".
# Which is always considered as true.
# The Configurator does not know anything about
# "%kernel.debug%" being a parameter.
In order to support this use case, the Configuration class has to be injected with this parameter via
the extension as follows:
Listing 20-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace AppBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
private $debug;
public function __construct($debug)
{
$this->debug = (bool) $debug;
}
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('my_bundle');
$rootNode
->children()
// ...
->booleanNode('logging')->defaultValue($this->debug)->end()
// ...
->end()
;
return $treeBuilder;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace AppBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class AppExtension extends Extension
{
// ...
public function getConfiguration(array $config, ContainerBuilder $container)
{
return new Configuration($container->getParameter('kernel.debug'));
}
}
$container->setParameter('assetic.debug', $config['debug']);
The string %kernel.debug% passed here as an argument handles the interpreting job to the
container which in turn does the evaluation. Both ways accomplish similar goals. AsseticBundle will
not use %kernel.debug% but rather the new %assetic.debug% parameter.
Chapter 21
1. https://github.com/symfony/symfony-standard
2. https://en.wikipedia.org/wiki/Front_Controller_pattern
3. https://github.com/symfony/symfony-standard
4. https://github.com/symfony/symfony-standard/blob/master/web/app.php
5. https://github.com/symfony/symfony-standard/blob/master/web/app_dev.php
Chapter 21: Understanding how the Front Controller, Kernel and Environments Work together | 71
Because every request is routed through it, the front controller can be used to perform global initialization
prior to setting up the kernel or to decorate6 the kernel with additional features. Examples include:
http://localhost/app_dev.php/some/path/...
As you can see, this URL contains the PHP script to be used as the front controller. You can use
that to easily switch the front controller or use a custom one by placing it in the web/ directory (e.g.
app_cache.php).
When using Apache and the RewriteRule shipped with the Symfony Standard Edition7, you can omit the
filename from the URL and the RewriteRule will use app.php as the default one.
Pretty much every other web server should be able to achieve a behavior similar to that of the
RewriteRule described above. Check your server documentation for details or see Configuring a Web
Server.
Make sure you appropriately secure your front controllers against unauthorized access. For example,
you don't want to make a debugging environment available to arbitrary users in your production
environment.
Technically, the app/console8 script used when running Symfony on the command line is also a front
controller, only that is not used for web, but for command line requests.
6. https://en.wikipedia.org/wiki/Decorator_pattern
7. https://github.com/symfony/symfony-standard/blob/master/web/.htaccess
8. https://github.com/symfony/symfony-standard/blob/master/app/console
9. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Kernel.html
10. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/HttpKernelInterface.html#method_handle
11. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelInterface.html
12. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Kernel.html
13. https://en.wikipedia.org/wiki/Template_method_pattern
14. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelInterface.html#method_registerBundles
15. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelInterface.html#method_registerContainerConfiguration
Chapter 21: Understanding how the Front Controller, Kernel and Environments Work together | 72
To fill these (small) blanks, your application needs to subclass the Kernel and implement these methods.
The resulting class is conventionally called the AppKernel.
Again, the Symfony Standard Edition provides an AppKernel16 in the app/ directory. This class uses
the name of the environment - which is passed to the Kernel's constructor17 method and is available
via getEnvironment()18 - to decide which bundles to create. The logic for that is in
registerBundles(), a method meant to be extended by you when you start adding bundles to your
application.
You are, of course, free to create your own, alternative or additional AppKernel variants. All you need
is to adapt your (or add a new) front controller to make use of the new kernel.
The name and location of the AppKernel is not fixed. When putting multiple Kernels into a single
application, it might therefore make sense to add additional sub-directories, for example app/
admin/AdminKernel.php and app/api/ApiKernel.php. All that matters is that your front
controller is able to create an instance of the appropriate kernel.
Having different AppKernels might be useful to enable different front controllers (on potentially
different servers) to run parts of your application independently (for example, the admin UI, the frontend UI and database migrations).
There's a lot more the AppKernel can be used for, for example overriding the default directory
structure. But odds are high that you don't need to change things like this on the fly by having several
AppKernel implementations.
The Environments
AppKernel has to implement another method registerContainerConfiguration()19. This method is responsible for loading the application's
As
just
mentioned,
the
16. https://github.com/symfony/symfony-standard/blob/master/app/AppKernel.php
17. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Kernel.html#method___construct
18. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Kernel.html#method_getEnvironment
19. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelInterface.html#method_registerContainerConfiguration
20. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelInterface.html#method_registerContainerConfiguration
21. https://github.com/symfony/symfony-standard/blob/master/app/AppKernel.php
Chapter 21: Understanding how the Front Controller, Kernel and Environments Work together | 73
Chapter 22
Environment Variables
Symfony will grab any environment variable prefixed with SYMFONY__ and set it as a parameter in the
service container. Some transformations are applied to the resulting parameter name:
SYMFONY__ prefix is removed;
Parameter name is lowercased;
Double underscores are replaced with a period, as a period is not a valid character in an
environment variable name.
For example, if you're using Apache, environment variables can be set using the following VirtualHost
configuration:
Listing 22-1
1
2
3
4
5
6
7
8
9
10
11
12
<VirtualHost *:80>
ServerName
DocumentRoot
DirectoryIndex
SetEnv
SetEnv
Symfony
"/path/to/symfony_2_app/web"
index.php index.html
SYMFONY__DATABASE__USER user
SYMFONY__DATABASE__PASSWORD secret
<Directory "/path/to/symfony_2_app/web">
AllowOverride All
Allow from All
</Directory>
</VirtualHost>
The example above is for an Apache configuration, using the SetEnv1 directive. However, this will
work for any web server which supports the setting of environment variables.
Also, in order for your console to work (which does not use Apache), you must export these as shell
variables. On a Unix system, you can run the following:
Listing 22-2
1
2
$ export SYMFONY__DATABASE__USER=user
$ export SYMFONY__DATABASE__PASSWORD=secret
Now that you have declared an environment variable, it will be present in the PHP $_SERVER global
variable. Symfony then automatically sets all $_SERVER variables prefixed with SYMFONY__ as
parameters in the service container.
You can now reference these parameters wherever you need them.
Listing 22-3
1
2
3
4
5
6
doctrine:
dbal:
driver
dbname:
user:
password:
pdo_mysql
symfony_project
'%database.user%'
'%database.password%'
Constants
The container also has support for setting PHP constants as parameters. See Constants as Parameters for
more details.
Miscellaneous Configuration
The imports directive can be used to pull in parameters stored elsewhere. Importing a PHP file gives
you the flexibility to add whatever is needed in the container. The following imports a file named
parameters.php.
Listing 22-4
1
2
3
# app/config/config.yml
imports:
- { resource: parameters.php }
A resource file can be one of many types. PHP, XML, YAML, INI, and closure resources are all
supported by the imports directive.
In parameters.php, tell the service container the parameters that you wish to set. This is useful when
important configuration is in a non-standard format. The example below includes a Drupal database
configuration in the Symfony service container.
Listing 22-5
1
2
3
// app/config/parameters.php
include_once('/path/to/drupal/sites/default/settings.php');
$container->setParameter('drupal.database.url', $db_url);
1. http://httpd.apache.org/docs/current/env.html
Chapter 23
Using the Apache Router is no longer considered a good practice. The small increase obtained
in the application routing performance is not worth the hassle of continuously updating the routes
configuration.
The Apache Router will be removed in Symfony 3 and it's highly recommended to not use it in your
applications.
Symfony, while fast out of the box, also provides various ways to increase that speed with a little bit of
tweaking. One of these ways is by letting Apache handle routes directly, rather than using Symfony for
this task.
Apache router was deprecated in Symfony 2.5 and will be removed in Symfony 3.0. Since the PHP
implementation of the Router was improved, performance gains were no longer significant (while it's
very hard to replicate the same behavior).
1
2
3
4
# app/config/config_prod.yml
parameters:
router.options.matcher.cache_class: ~ # disable router cache
router.options.matcher_class: Symfony\Component\Routing\Matcher\ApacheUrlMatcher
Note that ApacheUrlMatcher1 extends UrlMatcher2 so even if you don't regenerate the
mod_rewrite rules, everything will work (because at the end of ApacheUrlMatcher::match() a
call to parent::match() is done).
1. http://api.symfony.com/2.7/Symfony/Component/Routing/Matcher/ApacheUrlMatcher.html
2. http://api.symfony.com/2.7/Symfony/Component/Routing/Matcher/UrlMatcher.html
1
2
3
4
# app/config/routing.yml
hello:
path: /hello/{name}
defaults: { _controller: AppBundle:Greet:hello }
1
2
3
4
5
6
7
You can now rewrite web/.htaccess to use the new rules, so with this example it should look like this:
Listing 23-5
1
2
3
4
5
6
7
8
9
10
11
<IfModule mod_rewrite.c>
RewriteEngine On
The procedure above should be done each time you add/change a route if you want to take full
advantage of this setup.
Additional Tweaks
To save some processing time, change occurrences of Request to ApacheRequest in web/app.php:
Listing 23-6
1
2
3
4
5
6
7
8
9
10
// web/app.php
require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
// require_once __DIR__.'/../app/AppCache.php';
use Symfony\Component\HttpFoundation\ApacheRequest;
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
11
12
Chapter 24
1
2
3
4
5
6
7
8
9
10
11
12
<VirtualHost *:80>
ServerName domain.tld
ServerAlias www.domain.tld
DocumentRoot /var/www/project/web
<Directory /var/www/project/web>
AllowOverride All
Order Allow,Deny
Allow from All
</Directory>
13
14
15
16
17
18
19
20
your system supports the APACHE_LOG_DIR variable, you may want to use
${APACHE_LOG_DIR}/ instead of hardcoding /var/log/apache2/.
If
Use the following optimized configuration to disable .htaccess support and increase web server
performance:
Listing 24-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<VirtualHost *:80>
ServerName domain.tld
ServerAlias www.domain.tld
DocumentRoot /var/www/project/web
<Directory /var/www/project/web>
AllowOverride None
Order Allow,Deny
Allow from All
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>
</Directory>
#
#
#
#
#
If you are using php-cgi, Apache does not pass HTTP basic username and password to PHP by
default. To work around this limitation, you should use the following configuration snippet:
Listing 24-3
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Listing 24-4
1
2
3
4
<Directory /var/www/project/web>
Require all granted
# ...
</Directory>
For advanced Apache configuration options, read the official Apache documentation1.
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<VirtualHost *:80>
ServerName domain.tld
ServerAlias www.domain.tld
1. http://httpd.apache.org/docs/
2. https://bz.apache.org/bugzilla/show_bug.cgi?id=54101
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
DocumentRoot /var/www/project/web
<Directory /var/www/project/web>
# enable the .htaccess rewrites
AllowOverride All
Require all granted
</Directory>
#
#
#
#
#
ErrorLog /var/log/apache2/project_error.log
CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<VirtualHost *:80>
ServerName domain.tld
ServerAlias www.domain.tld
AddHandler php5-fcgi .php
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization
DocumentRoot /var/www/project/web
<Directory /var/www/project/web>
# enable the .htaccess rewrites
AllowOverride All
Order Allow,Deny
Allow from all
</Directory>
#
#
#
#
#
ErrorLog /var/log/apache2/project_error.log
CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>
If you prefer to use a Unix socket, you have to use the -socket option instead:
Listing 24-8
Nginx
The minimum configuration to get your application running under Nginx is:
Listing 24-9
1
2
server {
server_name domain.tld www.domain.tld;
3. http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
root /var/www/project/web;
location / {
# try to serve file directly, fallback to app.php
try_files $uri /app.php$is_args$args;
}
# DEV
# This rule should only be placed on your development environment
# In production, don't include this and don't deploy app_dev.php or config.php
location ~ ^/(app_dev|config)\.php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
# When you are using symlinks to link the document root to the
# current version of your application, you should pass the real
# application path instead of the path to the symlink to PHP
# FPM.
# Otherwise, PHP's OPcache may not properly detect changes to
# your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
# for more information).
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
}
# PROD
location ~ ^/app\.php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
# When you are using symlinks to link the document root to the
# current version of your application, you should pass the real
# application path instead of the path to the symlink to PHP
# FPM.
# Otherwise, PHP's OPcache may not properly detect changes to
# your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
# for more information).
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
# Prevents URIs that include the front controller. This will 404:
# http://domain.tld/app.php/some-path
# Remove the internal directive to allow URIs like this
internal;
}
# return 404 for all other php files not matching the front controller
# this prevents access to other php files you don't want to be accessible.
location ~ \.php$ {
return 404;
}
error_log /var/log/nginx/project_error.log;
access_log /var/log/nginx/project_access.log;
}
This executes only app.php, app_dev.php and config.php in the web directory. All other files
ending in ".php" will be denied.
If you have other PHP files in your web directory that need to be executed, be sure to include them
in the location block above.
After you deploy to production, make sure that you cannot access the app_dev.php or
config.php scripts (i.e. http://example.com/app_dev.php and http://example.com/
config.php). If you can access these, be sure to remove the DEV section from the above
configuration.
For advanced Nginx configuration options, read the official Nginx documentation4.
4. http://wiki.nginx.org/Symfony
Chapter 25
1
2
3
4
5
6
7
8
9
10
11
12
13
// app/AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
// ...
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
This method loads the app/config/config_dev.yml file for the dev environment and so on. In
turn, this file loads the common configuration file located at app/config/config.yml. Therefore,
the configuration files of the default Symfony Standard Edition follow this structure:
Listing 25-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<your-project>/
app/
config/
config.yml
config_dev.yml
config_prod.yml
config_test.yml
parameters.yml
parameters.yml.dist
routing.yml
routing_dev.yml
security.yml
src/
vendor/
web/
This default structure was chosen for its simplicity one file per environment. But as any other Symfony
feature, you can customize it to better suit your needs. The following sections explain different ways to
organize your configuration files. In order to simplify the examples, only the dev and prod environments
are taken into account.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<your-project>/
app/
config/
common/
config.yml
parameters.yml
routing.yml
security.yml
dev/
config.yml
parameters.yml
routing.yml
security.yml
prod/
config.yml
parameters.yml
routing.yml
security.yml
src/
vendor/
web/
1
2
3
4
5
6
7
8
9
10
11
12
13
// app/AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
// ...
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/'.$this->getEnvironment().'/config.yml');
}
}
Then, make sure that each config.yml file loads the rest of the configuration files, including the
common files. For instance, this would be the imports needed for the app/config/dev/config.yml
file:
Listing 25-5
1
2
3
4
5
6
7
# app/config/dev/config.yml
imports:
- { resource: '../common/config.yml' }
- { resource: 'parameters.yml' }
- { resource: 'security.yml' }
# ...
1. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelInterface.html#method_registerContainerConfiguration
Due to the way in which parameters are resolved, you cannot use them to build paths in imports
dynamically. This means that something like the following doesn't work:
Listing 25-6
1
2
3
# app/config/config.yml
imports:
- { resource: '%kernel.root_dir%/parameters.yml' }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<your-project>/
app/
config/
bundles/
bundle1.yml
bundle2.yml
...
bundleN.yml
environments/
common.yml
dev.yml
prod.yml
routing/
common.yml
dev.yml
prod.yml
services/
frontend.yml
backend.yml
...
security.yml
src/
vendor/
web/
1
2
3
4
5
6
7
8
9
10
11
12
13
// app/AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
// ...
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/environments/'.$this->getEnvironment().'.yml');
}
}
Following the same technique explained in the previous section, make sure to import the appropriate
configuration files from each main file (common.yml, dev.yml and prod.yml).
Advanced Techniques
Symfony loads configuration files using the Config component, which provides some advanced features.
PDF brought to you by
generated on July 28, 2016
1
2
3
4
5
6
7
8
# app/config/config.yml
imports:
- { resource: 'parameters.yml' }
- { resource: 'services.xml' }
- { resource: 'security.yml' }
- { resource: 'legacy.php' }
# ...
The IniFileLoader parses the file contents using the parse_ini_file2 function. Therefore,
you can only set parameters to string values. Use one of the other loaders if you want to use other
data types (e.g. boolean, integer, etc.).
If you use any other configuration format, you have to define your own loader class extending it from
FileLoader3. When the configuration values are dynamic, you can use the PHP configuration file
to execute your own logic. In addition, you can define your own services to load configurations from
databases or web services.
1
2
3
4
5
6
# app/config/config.yml
imports:
- { resource: 'parameters.yml' }
- { resource: '/etc/sites/mysite.com/parameters.yml' }
# ...
Most of the time, local developers won't have the same files that exist on the production servers. For that
reason, the Config component provides the ignore_errors option to silently discard errors when the
loaded file doesn't exist:
Listing 25-11
1
2
3
4
5
6
# app/config/config.yml
imports:
- { resource: 'parameters.yml' }
- { resource: '/etc/sites/mysite.com/parameters.yml', ignore_errors: true }
# ...
As you've seen, there are lots of ways to organize your configuration files. You can choose one of these or
even create your own custom way of organizing the files. Don't feel limited by the Standard Edition that
comes with Symfony. For even more customization, see "How to Override Symfony's default Directory
Structure".
2. http://php.net/manual/en/function.parse-ini-file.php
3. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Loader/FileLoader.html
Chapter 26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Command/GreetCommand.php
namespace AppBundle\Command;
use
use
use
use
use
Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
Symfony\Component\Console\Input\InputArgument;
Symfony\Component\Console\Input\InputInterface;
Symfony\Component\Console\Input\InputOption;
Symfony\Component\Console\Output\OutputInterface;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if ($name) {
$text = 'Hello '.$name;
} else {
$text = 'Hello';
}
if ($input->getOption('yell')) {
$text = strtoupper($text);
}
$output->writeln($text);
}
}
1
2
3
4
5
6
7
8
1. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.html
2. http://api.symfony.com/2.7/Symfony/Component/Console/Command/Command.html
Testing Commands
When
testing
commands
used
as
part
of
the
full-stack
framework,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use AppBundle\Command\GreetCommand;
class ListCommandTest extends \PHPUnit_Framework_TestCase
{
public function testExecute()
{
// mock the Kernel or create one depending on your needs
$application = new Application($kernel);
$application->add(new GreetCommand());
$command = $application->find('demo:greet');
$commandTester = new CommandTester($command);
$commandTester->execute(
array(
'name'
=> 'Fabien',
'--yell' => true,
)
);
$this->assertRegExp('/.../', $commandTester->getDisplay());
// ...
}
}
In the specific case above, the name parameter and the --yell option are not mandatory for the
command to work, but are shown so you can see how to customize them when calling the command.
To be able to use the fully set up service container for your console tests you can extend your test from
KernelTestCase5:
Listing 26-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use
use
use
use
Symfony\Component\Console\Tester\CommandTester;
Symfony\Bundle\FrameworkBundle\Console\Application;
Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
AppBundle\Command\GreetCommand;
3. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Console/Application.html
4. http://api.symfony.com/2.7/Symfony/Component/Console/Application.html
5. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.html
22
23
24
25
26
27
28
29
)
);
$this->assertRegExp('/.../', $commandTester->getDisplay());
// ...
}
}
Chapter 27
or the equivalent:
Listing 27-2
In addition to changing the environment, you can also choose to disable debug mode. This can be useful
where you want to run commands in the dev environment but avoid the performance hit of collecting
debug data:
Listing 27-3
There is an interactive shell which allows you to enter commands without having to specify php app/
console each time, which is useful if you need to run several commands. To enter the shell run:
Listing 27-4
1
2
You can now just run commands with the command name:
Listing 27-5
When using the shell you can choose to run each command in a separate process:
Listing 27-6
1
2
When you do this, the output will not be colorized and interactivity is not supported so you will need to
pass all command parameters explicitly.
Unless you are using isolated processes, clearing the cache in the shell will not have an effect on
subsequent commands you run. This is because the original cached files are still being used.
Chapter 28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/AppBundle/Command/GreetCommand.php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class GreetCommand extends ContainerAwareCommand
{
// ...
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(array(
'<info>Lorem Ipsum Dolor Sit Amet</>',
'<info>==========================</>',
'',
));
// ...
}
}
Displaying a simple title requires three lines of code, to change the font color, underline the contents and
leave an additional blank line after the title. Dealing with styles is required for well-designed commands,
but it complicates their code unnecessarily.
In order to reduce that boilerplate code, Symfony commands can optionally use the Symfony Style
Guide. These styles are implemented as a set of helper methods which allow to create semantic
commands and forget about their styling.
Basic Usage
In your command, instantiate the SymfonyStyle1 class and pass the $input and $output variables
as its arguments. Then, you can start using any of its helpers, such as title(), which displays the title
of the command:
Listing 28-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AppBundle/Command/GreetCommand.php
namespace AppBundle\Command;
use
use
use
use
Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
Symfony\Component\Console\Style\SymfonyStyle;
Symfony\Component\Console\Input\InputInterface;
Symfony\Component\Console\Output\OutputInterface;
// ...
}
}
Helper Methods
The SymfonyStyle2 class defines some helper methods that cover the most common interactions
performed by console commands.
Titling Methods
title()3
It displays the given string as the command title. This method is meant to be used only once in a
given command, but nothing prevents you to use it repeatedly:
Listing 28-3
section()4
It displays the given string as the title of some command section. This is only needed in complex
commands which want to better separate their contents:
Listing 28-4
1
2
3
4
5
6
7
$io->section('Adding a User');
// ...
$io->section('Generating the Password');
// ...
1. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html
2. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html
3. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_title
4. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_section
Content Methods
text()5
It displays the given string or array of strings as regular text. This is useful to render help messages
and instructions for the user running the command:
Listing 28-5
1
2
3
4
5
6
7
8
9
10
11
// ...
// consider using arrays when displaying long messages
$io->text(array(
'Lorem ipsum dolor sit amet',
'Consectetur adipiscing elit',
'Aenean sit amet arcu vitae sem faucibus porta',
));
listing()6
1
2
3
4
5
$io->listing(array(
'Element #1 Lorem ipsum dolor sit amet',
'Element #2 Lorem ipsum dolor sit amet',
'Element #3 Lorem ipsum dolor sit amet',
));
table()7
1
2
3
4
5
6
7
8
$io->table(
array('Header 1', 'Header 2'),
array(
array('Cell 1-1', 'Cell 1-2'),
array('Cell 2-1', 'Cell 2-2'),
array('Cell 3-1', 'Cell 3-2'),
)
);
newLine()8
It displays a blank line in the command output. Although it may seem useful, most of the times you
won't need it at all. The reason is that every helper already adds their own blank lines, so you don't
have to care about the vertical spacing:
Listing 28-8
5.
6.
7.
8.
1
2
3
4
5
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_text
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_listing
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_table
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_newLine
Admonition Methods
note()9
It displays the given string or array of strings as a highlighted admonition. Use this helper sparingly
to avoid cluttering command's output:
Listing 28-9
1
2
3
4
5
6
7
8
9
10
11
caution()10
Similar to the note() helper, but the contents are more prominently highlighted. The resulting
contents resemble an error message, so you should avoid using this helper unless strictly necessary:
Listing 28-10
1
2
3
4
5
6
7
8
9
10
11
It displays a progress bar with a number of steps equal to the argument passed to the method (don't
pass any value if the length of the progress bar is unknown):
Listing 28-11
1
2
3
4
5
progressAdvance()12
It makes the progress bar advance the given number of steps (or 1 step if no argument is passed):
Listing 28-12
9.
10.
11.
12.
1
2
3
4
5
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_note
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_caution
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_progressStart
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_progressAdvance
progressFinish()13
It finishes the progress bar (filling up all the remaining steps when its length is known):
Listing 28-13
$io->progressFinish();
You can pass the default value as the second argument so the user can simply hit the <Enter> key
to select that value:
Listing 28-15
In case you need to validate the given value, pass a callback validator as the third argument:
Listing 28-16
1
2
3
4
5
6
7
askHidden()15
It's very similar to the ask() method but the user's input will be hidden and it cannot define a
default value. Use it when asking for sensitive information:
Listing 28-17
1
2
3
4
5
6
7
8
9
10
confirm()16
It asks a Yes/No question to the user and it only returns true or false:
Listing 28-18
You can pass the default value as the second argument so the user can simply hit the <Enter> key
to select that value:
Listing 28-19
choice()17
It asks a question whose answer is constrained to the given list of valid answers:
Listing 28-20
13.
14.
15.
16.
17.
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_progressFinish
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_ask
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_askHidden
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_confirm
http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_choice
You can pass the default value as the third argument so the user can simply hit the <Enter> key to
select that value:
Listing 28-21
Result Methods
success()18
It displays the given string or array of strings highlighted as a successful message (with a green
background and the [OK] label). It's meant to be used once to display the final result of executing
the given command, but you can use it repeatedly during the execution of the command:
Listing 28-22
1
2
3
4
5
6
7
8
9
10
warning()19
It displays the given string or array of strings highlighted as a warning message (with a red
background and the [WARNING] label). It's meant to be used once to display the final result of
executing the given command, but you can use it repeatedly during the execution of the command:
Listing 28-23
1
2
3
4
5
6
7
8
9
10
error()20
It displays the given string or array of strings highlighted as an error message (with a red background
and the [ERROR] label). It's meant to be used once to display the final result of executing the given
command, but you can use it repeatedly during the execution of the command:
Listing 28-24
1
2
3
4
5
6
7
8
9
10
18. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_success
19. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_warning
20. http://api.symfony.com/2.7/Symfony/Component/Console/Style/SymfonyStyle.html#method_error
1
2
3
4
5
6
7
8
namespace AppBundle\Console;
use Symfony\Component\Console\Style\StyleInterface;
class CustomStyle implements StyleInterface
{
// ...implement the methods of the interface
}
Then, instantiate this custom class instead of the default SymfonyStyle in your commands. Thanks
to the StyleInterface you won't need to change the code of your commands to change their
appearance:
Listing 28-26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace AppBundle\Console;
use
use
use
use
AppBundle\Console\CustomStyle;
Symfony\Component\Console\Input\InputInterface;
Symfony\Component\Console\Output\OutputInterface;
Symfony\Component\Console\Style\SymfonyStyle;
// After
$io = new CustomStyle($input, $output);
// ...
}
}
21. http://api.symfony.com/2.7/Symfony/Component/Console/Style/StyleInterface.html
Chapter 29
Imagine you want to send spooled Swift Mailer messages by using the swiftmailer:spool:send command.
Run this command from inside your controller via:
Listing 29-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/AppBundle/Controller/SpoolController.php
namespace AppBundle\Controller;
use
use
use
use
use
Symfony\Bundle\FrameworkBundle\Console\Application;
Symfony\Bundle\FrameworkBundle\Controller\Controller;
Symfony\Component\Console\Input\ArrayInput;
Symfony\Component\Console\Output\BufferedOutput;
Symfony\Component\HttpFoundation\Response;
26
27
28
29
30
31
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Controller/SpoolController.php
namespace AppBundle\Controller;
use SensioLabs\AnsiConverter\AnsiToHtmlConverter;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Response;
// ...
class SpoolController extends Controller
{
public function sendSpoolAction($messages = 10)
{
// ...
$output = new BufferedOutput(
OutputInterface::VERBOSITY_NORMAL,
true // true for decorated
);
// ...
The AnsiToHtmlConverter can also be registered as a Twig Extension2, and supports optional
themes.
1. https://github.com/sensiolabs/ansi-to-html
2. https://github.com/sensiolabs/ansi-to-html#twig-integration
Chapter 30
# app/config/parameters.yml
parameters:
router.request_context.host: example.org
router.request_context.scheme: https
router.request_context.base_url: my/path
1
2
3
4
5
1
2
3
4
5
// src/AppBundle/Command/DemoCommand.php
// ...
class DemoCommand extends ContainerAwareCommand
{
6
7
8
9
10
11
12
13
14
15
Chapter 31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/AppBundle/Command/GreetCommand.php
namespace AppBundle\Command;
use
use
use
use
use
use
Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
Symfony\Component\Console\Input\InputArgument;
Symfony\Component\Console\Input\InputInterface;
Symfony\Component\Console\Input\InputOption;
Symfony\Component\Console\Output\OutputInterface;
Psr\Log\LoggerInterface;
1. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.html
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Depending on the environment in which you run your command (and your logging setup), you should
see the logged entries in app/logs/dev.log or app/logs/prod.log.
1
2
3
4
5
6
7
# app/config/services.yml
services:
app.listener.command_exception:
class: AppBundle\EventListener\ConsoleExceptionListener
arguments: ['@logger']
tags:
- { name: kernel.event_listener, event: console.exception }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/EventListener/ConsoleExceptionListener.php
namespace AppBundle\EventListener;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Psr\Log\LoggerInterface;
class ConsoleExceptionListener
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function onConsoleException(ConsoleExceptionEvent $event)
{
$command = $event->getCommand();
$exception = $event->getException();
$message = sprintf(
'%s: %s (uncaught exception) at %s line %s while running console command `%s`',
get_class($exception),
24
25
26
27
28
29
30
31
32
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
$command->getName()
);
$this->logger->error($message, array('exception' => $exception));
}
}
In the code above, when any command throws an exception, the listener will receive an event. You
can simply log it by passing the logger service via the service configuration. Your method receives a
ConsoleExceptionEvent2 object, which has methods to get information about the event and the
exception.
1
2
3
4
5
6
7
# app/config/services.yml
services:
app.listener.command_error:
class: AppBundle\EventListener\ErrorLoggerListener
arguments: ['@logger']
tags:
- { name: kernel.event_listener, event: console.terminate }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/EventListener/ErrorLoggerListener.php
namespace AppBundle\EventListener;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Psr\Log\LoggerInterface;
class ErrorLoggerListener
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function onConsoleTerminate(ConsoleTerminateEvent $event)
{
$statusCode = $event->getExitCode();
$command = $event->getCommand();
if ($statusCode === 0) {
return;
}
if ($statusCode > 255) {
$statusCode = 255;
$event->setExitCode($statusCode);
}
$this->logger->warning(sprintf(
2. http://api.symfony.com/2.7/Symfony/Component/Console/Event/ConsoleExceptionEvent.html
31
32
33
34
35
36
Chapter 32
1
2
3
4
5
6
# app/config/config.yml
services:
app.command.my_command:
class: AppBundle\Command\MyCommand
tags:
- { name: console.command }
1. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.html
constructor. For example, suppose you store the default value in some %command.default_name%
parameter:
Listing 32-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/AppBundle/Command/GreetCommand.php
namespace AppBundle\Command;
use
use
use
use
Symfony\Component\Console\Command\Command;
Symfony\Component\Console\Input\InputInterface;
Symfony\Component\Console\Input\InputOption;
Symfony\Component\Console\Output\OutputInterface;
Now, just update the arguments of your service configuration like normal to inject the
command.default_name parameter:
Listing 32-3
1
2
3
4
5
6
7
8
9
10
# app/config/config.yml
parameters:
command.default_name: Javier
services:
app.command.my_command:
class: AppBundle\Command\MyCommand
arguments: ["%command.default_name%"]
tags:
- { name: console.command }
Chapter 33
Since these pages contain a lot of sensitive internal information, Symfony won't display them in the
production environment. Instead, it'll show a simple and generic error page:
Error pages for the production environment can be customized in different ways depending on your
needs:
1. If you just want to change the contents and styles of the error pages to match the rest of your
application, override the default error templates;
2. If you also want to tweak the logic used by Symfony to generate error pages, override the default
exception controller;
3. If you need total control of exception handling to execute your own logic use the
kernel.exception event.
1
2
3
4
5
6
7
8
9
10
11
app/
Resources/
TwigBundle/
views/
Exception/
error404.html.twig
error403.html.twig
error.html.twig
error404.json.twig
error403.json.twig
error.json.twig
1. http://api.symfony.com/2.7/Symfony/Bundle/TwigBundle/Controller/ExceptionController.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{# app/Resources/TwigBundle/views/Exception/error404.html.twig #}
{% extends 'base.html.twig' %}
{% block body %}
<h1>Page not found</h1>
In case you need them, the ExceptionController passes some information to the error template
via the status_code and status_text variables that store the HTTP status code and message
respectively.
You can customize the status code by implementing HttpExceptionInterface2 and its required
getStatusCode() method. Otherwise, the status_code will default to 500.
The exception pages shown in the development environment can be customized in the same way
as error pages. Create a new exception.html.twig template for the standard HTML exception
page or exception.json.twig for the JSON exception page.
1
2
3
New in version 2.6: This feature was introduced in Symfony 2.6. Before, the third-party
WebfactoryExceptionsBundle3 could be used for the same purpose.
To use this feature, you need to have a definition in your routing_dev.yml file like so:
Listing 33-4
1
2
3
4
# app/config/routing_dev.yml
_errors:
resource: "@TwigBundle/Resources/config/routing/errors.xml"
prefix:
/_error
If you're coming from an older version of Symfony, you might need to add this to your
routing_dev.yml file. If you're starting from scratch, the Symfony Standard Edition4 already contains
it for you.
With this route added, you can use URLs like
Listing 33-5
1
2
http://localhost/app_dev.php/_error/{statusCode}
http://localhost/app_dev.php/_error/{statusCode}.{format}
to preview the error page for a given status code as HTML or for a given status code and format.
1
2
3
# app/config/config.yml
twig:
exception_controller: AppBundle:Exception:showException
3. https://github.com/webfactory/exceptions-bundle
4. https://github.com/symfony/symfony-standard/
5. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/EventListener/ExceptionListener.html
6. http://api.symfony.com/2.7//Symfony/Component/Debug/Exception/FlattenException.html
7. http://api.symfony.com/2.7//Symfony/Component/HttpKernel/Log/DebugLoggerInterface.html
8. http://api.symfony.com/2.7/Symfony/Bundle/TwigBundle/Controller/ExceptionController.html
In case of extending the ExceptionController9 you may configure a service to pass the Twig
environment and the debug flag to the constructor.
Listing 33-7
1
2
3
4
5
# app/config/services.yml
services:
app.exception_controller:
class: AppBundle\Controller\CustomExceptionController
arguments: ['@twig', '%kernel.debug%']
And then configure twig.exception_controller using the controller as services syntax (e.g.
app.exception_controller:showAction).
The error page preview also works for your own controllers set up this way.
This approach allows you to create centralized and layered error handling: instead of catching (and
handling) the same exceptions in various controllers time and again, you can have just one (or several)
listeners deal with them.
See ExceptionListener12 class code for a real example of an advanced listener of this type.
This listener handles various security-related exceptions that are thrown in your application (like
AccessDeniedException13) and takes measures like redirecting the user to the login page,
logging them out and other things.
9. http://api.symfony.com/2.7/Symfony/Bundle/TwigBundle/Controller/ExceptionController.html
10. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/HttpKernel.html
11. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Event/GetResponseForExceptionEvent.html
12. http://api.symfony.com/2.7/Symfony/Component/Security/Http/Firewall/ExceptionListener.html
13. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Exception/AccessDeniedException.html
Chapter 34
Defining controllers as services is not officially recommended by Symfony. They are used by
some developers for very specific use cases, such as DDD (domain-driven design) and Hexagonal
Architecture applications.
In the book, you've learned how easily a controller can be used when it extends the base Controller1
class. While this works fine, controllers can also be specified as services. Even if you don't specify your
controllers as services, you might see them being used in some open-source Symfony bundles, so it may
be useful to understand both approaches.
These are the main advantages of defining controllers as services:
The entire controller and any service passed to it can be modified via the service container
configuration. This is useful when developing reusable bundles;
Your controllers are more "sandboxed". By looking at the constructor arguments, it's easy to see
what types of things this controller may or may not do;
Since dependencies must be injected manually, it's more obvious when your controller is becoming
too big (i.e. if you have many constructor arguments).
These are the main drawbacks of defining controllers as services:
It takes more work to create the controllers because they don't have automatic access to the services
or to the base controller shortcuts;
The constructor of the controllers can rapidly become too complex because you must inject every
single dependency needed by them;
The code of the controllers is more verbose because you can't use the shortcuts of the base controller
and you must replace them with some lines of code.
The recommendation from the best practices is also valid for controllers defined as services: avoid putting
your business logic into the controllers. Instead, inject services that do the bulk of the work.
1. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class HelloController
{
public function indexAction($name)
{
return new Response('<html><body>Hello '.$name.'!</body></html>');
}
}
1
2
3
4
# app/config/services.yml
services:
app.hello_controller:
class: AppBundle\Controller\HelloController
You cannot drop the Action part of the method name when using this syntax.
You can also route to the service by using the same notation when defining the route _controller
value:
Listing 34-4
1
2
3
4
# app/config/routing.yml
hello:
path:
/hello
defaults: { _controller: app.hello_controller:indexAction }
You can also use annotations to configure routing using a controller defined as a service. Make sure
you specify the service ID in the @Route annotation. See the FrameworkExtraBundle documentation2
for details.
If your controller implements the __invoke() method, you can simply refer to the service id
(app.hello_controller).
New in version 2.6: Support for __invoke() was introduced in Symfony 2.6.
2. https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html#controller-as-service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class HelloController extends Controller
{
public function indexAction($name)
{
return $this->render(
'AppBundle:Hello:index.html.twig',
array('name' => $name)
);
}
}
If you look at the source code for the render function in Symfony's base Controller class4, you'll see that
this method actually uses the templating service:
Listing 34-6
In a controller that's defined as a service, you can instead inject the templating service and use it
directly:
Listing 34-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;
class HelloController
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function indexAction($name)
{
return $this->templating->renderResponse(
'AppBundle:Hello:index.html.twig',
array('name' => $name)
);
}
}
The service definition also needs modifying to specify the constructor argument:
3. https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
4. https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
Listing 34-8
1
2
3
4
5
# app/config/services.yml
services:
app.hello_controller:
class:
AppBundle\Controller\HelloController
arguments: ['@templating']
Rather than fetching the templating service from the container, you can inject only the exact service(s)
that you need directly into the controller.
This does not mean that you cannot extend these controllers from your own base controller. The
move away from the standard base controller is because its helper methods rely on having the
container available which is not the case for controllers that are defined as services. It may be a
good idea to extract common code into a service that's injected rather than place that code into a
base controller that you extend. Both approaches are valid, exactly how you want to organize your
reusable code is up to you.
createNotFoundException()7
Listing 34-11
1
2
3
4
5
6
7
use Symfony\Component\HttpKernel\HttpKernelInterface;
// ...
$request = ...;
$attributes = array_merge($path, array('_controller' => $controller));
$subRequest = $request->duplicate($query, null, $attributes);
$httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
5.
6.
7.
8.
9.
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_createForm
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_createFormBuilder
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_createNotFoundException
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_forward
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_generateUrl
10. http://api.symfony.com/2.7/Symfony/Component/Routing/Generator/UrlGeneratorInterface.html
1
2
3
4
5
$user = null;
$token = $tokenStorage->getToken();
if (null !== $token && is_object($token->getUser())) {
$user = $token->getUser();
}
$authChecker->isGranted($attributes, $object);
redirect()14
Listing 34-16
1
2
3
use Symfony\Component\HttpFoundation\RedirectResponse;
return new RedirectResponse($url, $status);
$templating->render($view, $parameters);
1
2
3
4
5
6
7
8
use Symfony\Component\HttpFoundation\StreamedResponse;
$templating = $this->templating;
$callback = function () use ($templating, $view, $parameters) {
$templating->stream($view, $parameters);
}
return new StreamedResponse($callback);
getRequest has been deprecated. Instead, have an argument to your controller action method
called Request $request. The order of the parameters is not important, but the typehint must
be provided.
11.
12.
13.
14.
15.
16.
17.
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_getDoctrine
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_getUser
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_isGranted
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_redirect
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_render
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_renderView
http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_stream
Chapter 35
Instead of handling file uploading yourself, you may consider using the VichUploaderBundle1
community bundle. This bundle provides all the common operations (such as file renaming, saving
and deleting) and it's tightly integrated with Doctrine ORM, MongoDB ODM, PHPCR ODM and
Propel.
Imagine that you have a Product entity in your application and you want to add a PDF brochure for
each product. To do so, add a new property called brochure in the Product entity:
Listing 35-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
class Product
{
// ...
/**
* @ORM\Column(type="string")
*
* @Assert\NotBlank(message="Please, upload the product brochure as a PDF file.")
* @Assert\File(mimeTypes={ "application/pdf" })
*/
private $brochure;
public function getBrochure()
{
return $this->brochure;
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
}
1. https://github.com/dustin10/VichUploaderBundle
Note that the type of the brochure column is string instead of binary or blob because it just stores
the PDF file name instead of the file contents.
Then, add a new brochure field to the form that manages the Product entity:
Listing 35-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Form/ProductType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('brochure', 'file', array('label' => 'Brochure (PDF file)'))
// ...
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product',
));
}
public function getName()
{
return 'product';
}
}
Now, update the template that renders the form to display the new brochure field (the exact template
code to add depends on the method used by your application to customize form rendering):
Listing 35-3
1
2
3
4
5
6
7
8
{# app/Resources/views/product/new.html.twig #}
<h1>Adding a new product</h1>
{{ form_start(form) }}
{# ... #}
{{ form_row(form.brochure) }}
{{ form_end(form) }}
Finally, you need to update the code of the controller that handles the form:
Listing 35-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/AppBundle/Controller/ProductController.php
namespace AppBundle\ProductController;
use
use
use
use
use
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
Symfony\Bundle\FrameworkBundle\Controller\Controller;
Symfony\Component\HttpFoundation\Request;
AppBundle\Entity\Product;
AppBundle\Form\ProductType;
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Now, create the brochures_directory parameter that was used in the controller to specify the
directory in which the brochures should be stored:
Listing 35-5
1
2
3
4
5
# app/config/config.yml
# ...
parameters:
brochures_directory: '%kernel.root_dir%/../web/uploads/brochures'
There are some important things to consider in the code of the above controller:
1. When the form is uploaded, the brochure property contains the whole PDF file contents. Since
this property stores just the file name, you must set its new value before persisting the changes
of the entity;
2. In Symfony applications, uploaded files are objects of the UploadedFile2 class. This class provides
methods for the most common operations when dealing with uploaded files;
3. A well-known security best practice is to never trust the input provided by users. This also
applies to the files uploaded by your visitors. The UploadedFile class provides methods to get the
original file extension (getExtension()3), the original file size (getClientSize()4) and the original file
name (getClientOriginalName()5). However, they are considered not safe because a malicious user
could tamper that information. That's why it's always better to generate a unique name and use
the guessExtension()6 method to let Symfony guess the right extension according to the file MIME
type;
You can use the following code to link to the PDF brochure of a product:
Listing 35-6
2.
3.
4.
5.
6.
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getExtension
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getClientSize
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_getClientOriginalName
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html#method_guessExtension
When creating a form to edit an already persisted item, the file form type still expects a File7
instance. As the persisted entity now contains only the relative file path, you first have to concatenate
the configured upload path with the stored filename and create a new File class:
Listing 35-7
1
2
3
4
5
6
use Symfony\Component\HttpFoundation\File\File;
// ...
$product->setBrochure(
new File($this->getParameter('brochures_directory').'/'.$product->getBrochure())
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/FileUploader.php
namespace AppBundle;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileUploader
{
private $targetDir;
public function __construct($targetDir)
{
$this->targetDir = $targetDir;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->targetDir, $fileName);
return $fileName;
}
}
1
2
3
4
5
6
# app/config/services.yml
services:
# ...
app.brochure_uploader:
class: AppBundle\FileUploader
arguments: ['%brochures_directory%']
1
2
3
4
5
6
7
8
9
10
11
// src/AppBundle/Controller/ProductController.php
// ...
public function newAction(Request $request)
{
// ...
if ($form->isValid()) {
$file = $product->getBrochure();
$fileName = $this->get('app.brochure_uploader')->upload($file);
7. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/File.html
12
13
14
15
16
17
18
$product->setBrochure($fileName);
// ...
}
// ...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// src/AppBundle/EventListener/BrochureUploadListener.php
namespace AppBundle\EventListener;
use
use
use
use
use
Symfony\Component\HttpFoundation\File\UploadedFile;
Doctrine\ORM\Event\LifecycleEventArgs;
Doctrine\ORM\Event\PreUpdateEventArgs;
AppBundle\Entity\Product;
AppBundle\FileUploader;
class BrochureUploadListener
{
private $uploader;
public function __construct(FileUploader $uploader)
{
$this->uploader = $uploader;
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$this->uploadFile($entity);
}
private function uploadFile($entity)
{
// upload only works for Product entities
if (!$entity instanceof Product) {
return;
}
$file = $entity->getBrochure();
Listing 35-12
1
2
3
4
5
6
7
8
9
# app/config/services.yml
services:
# ...
app.doctrine_brochure_listener:
class: AppBundle\EventListener\BrochureUploadListener
arguments: ['@app.brochure_uploader']
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }
This listeners is now automatically executed when persisting a new Product entity. This way, you can
remove everything related to uploading from the controller.
This listener can also create the File instance based on the path when fetching entities from the
database:
Listing 35-13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ...
use Symfony\Component\HttpFoundation\File\File;
// ...
class BrochureUploadListener
{
// ...
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$fileName = $entity->getBrochure();
$entity->setBrochure(new File($this->targetPath.'/'.$fileName));
}
}
After adding these lines, configure the listener to also listen for the postLoad event.
Chapter 36
1
2
3
4
5
6
7
8
// ...
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
To make your debugger happier, disable all PHP class caches by removing the call to
loadClassCache() and by replacing the require statements like below:
Listing 36-2
1
2
3
// ...
// $loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Chapter 36: How to Optimize your Development Environment for Debugging | 128
4
5
6
7
8
9
If you disable the PHP caches, don't forget to revert after your debugging session.
Some IDEs do not like the fact that some classes are stored in different locations. To avoid problems, you
can either tell your IDE to ignore the PHP cache files, or you can change the extension used by Symfony
for these files:
Listing 36-3
$kernel->loadClassCache('classes', '.php.cache');
Chapter 36: How to Optimize your Development Environment for Debugging | 129
Chapter 37
Deploying can be a complex and varied task depending on the setup and the requirements of
your application. This article is not a step-by-step guide, but is a general list of the most common
requirements and ideas for deployment.
Tagging a particular version of your code as a release in your source control repository;
Creating a temporary staging area to build your updated setup "offline";
Running any tests available to ensure code and/or server stability;
Removal of any unnecessary files from the web/ directory to keep your production environment
clean;
Clearing of external cache systems (like Memcached1 or Redis2).
1. http://memcached.org/
2. http://redis.io/
3. http://capistranorb.com/
4. https://github.com/capistrano/symfony/
5. http://capistranorb.com/
6. https://github.com/capistrano/symfony/
7. http://capifony.org/
8. https://github.com/liip/sf2debpkg
9. https://github.com/andres-montanez/Magallanes
10. http://www.fabfile.org/
11. http://deployer.org/
12. http://knpbundles.com/search?q=deploy
13. http://blog.sznapka.pl/deploying-symfony2-applications-with-ant
A) Check Requirements
Check if your server meets the requirements by running:
Listing 37-1
$ php app/check.php
F) Other Things!
There may be lots of other things that you need to do, depending on your setup:
install)
Chapter 38
1. https://signup.live.com/signup.aspx
2. https://manage.windowsazure.com
For the URL, enter the URL that you would like to use for your Symfony application, then pick Create
new web hosting plan in the region you want. By default, a free 20 MB SQL database is selected in the
database dropdown list. In this tutorial, the Symfony app will connect to a MySQL database. Pick the
Create a new MySQL database option in the dropdown list. You can keep the DefaultConnection
string name. Finally, check the box Publish from source control to enable a Git repository and go to
the next step.
Agree to the terms and conditions and click on the right arrow to continue.
Congratulations! Your Azure Website is now up and running. You can check it by browsing to the
Website url you configured in the first step. You should see the following display in your web browser:
The Microsoft Azure portal also provides a complete control panel for the Azure Website.
Your Azure Website is ready! But to run a Symfony site, you need to configure just a few additional
things.
Click the Save button in the bottom bar to save your changes and restart the web server.
Choosing a more recent PHP version can greatly improve runtime performance. PHP 5.5 ships with
a new built-in PHP accelerator called OPCache that replaces APC. On an Azure Website, OPCache
is already enabled and there is no need to install and set up APC.
The following screenshot shows the output of a phpinfo3 script run from an Azure Website to
verify that PHP 5.5 is running with OPCache enabled.
1
2
3
4
; .user.ini
expose_php = Off
memory_limit = 256M
upload_max_filesize = 10M
3. http://php.net/manual/en/function.phpinfo.php
None of these settings needs to be overridden. The default PHP configuration is already pretty good, so
this is just an example to show how you can easily tweak PHP internal settings by uploading your custom
.ini file.
You can either manually create this file on your Azure Website FTP server under the site/wwwroot
directory or deploy it with Git. You can get your FTP server credentials from the Azure Website Control
panel under the Dashboard tab on the right sidebar. If you want to use Git, simply put your .user.ini
file at the root of your local repository and push your commits to your Azure Website repository.
This cookbook has a section dedicated to explaining how to configure your Azure Website Git
repository and how to push the commits to be deployed. See Deploying from Git. You can also learn
more about configuring PHP internal settings on the official PHP MSDN documentation4 page.
To get the php_intl.dll file under your site/wwwroot directory, simply access the online Kudu
tool by browsing to the following URL:
Listing 38-2
https://[your-website-name].scm.azurewebsites.net
Kudu is a set of tools to manage your application. It comes with a file explorer, a command line prompt,
a log stream and a configuration settings summary page. Of course, this section can only be accessed if
you're logged in to your main Azure Website account.
4. http://blogs.msdn.com/b/silverlining/archive/2012/07/10/configuring-php-in-windows-azure-websites-with-user-ini-files.aspx
From the Kudu front page, click on the Debug Console navigation item in the main menu and choose
CMD. This should open the Debug Console page that shows a file explorer and a console prompt
below.
In the console prompt, type the following three commands to copy the original php_intl.dll
extension file into a custom website ext/ directory. This new directory must be created under the main
directory site/wwwroot.
Listing 38-3
1
2
3
$ cd site\wwwroot
$ mkdir ext
$ copy "D:\Program Files (x86)\PHP\v5.5\ext\php_intl.dll" ext
To complete the activation of the php_intl.dll extension, you must tell Azure Website to load it
from the newly created ext directory. This can be done by registering a global PHP_EXTENSIONS
environment variable from the Configure tab of the main Azure Website Control panel.
In the app settings section, register the PHP_EXTENSIONS environment variable with the value
ext\php_intl.dll as shown in the screenshot below:
Hit "save" to confirm your changes and restart the web server. The PHP Intl extension should now
be available in your web server environment. The following screenshot of a phpinfo5 page verifies the
intl extension is properly enabled:
Great! The PHP environment setup is now complete. Next, you'll learn how to configure the Git
repository and push code to production. You'll also learn how to install and configure the Symfony app
after it's deployed.
$ git --version
Get your Git from the git-scm.com6 website and follow the instructions to install and configure it on
your local machine.
In the Azure Website Control panel, browse the Deployment tab to get the Git repository URL where
you should push your code:
5. http://php.net/manual/en/function.phpinfo.php
6. http://git-scm.com/download
Now, you'll want to connect your local Symfony application with this remote Git repository on Azure
Website. If your Symfony application is not yet stored with Git, you must first create a Git repository
in your Symfony application directory with the git init command and commit to it with the git
commit command.
Also, make sure your Symfony repository has a .gitignore file at its root directory with at least the
following contents:
Listing 38-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/app/bootstrap.php.cache
/app/cache/*
/app/config/parameters.yml
/app/logs/*
!app/cache/.gitkeep
!app/logs/.gitkeep
/app/SymfonyRequirements.php
/build/
/vendor/
/bin/
/composer.phar
/web/app_dev.php
/web/bundles/
/web/config.php
The .gitignore file asks Git not to track any of the files and directories that match these patterns. This
means these files won't be deployed to the Azure Website.
Now, from the command line on your local machine, type the following at the root of your Symfony
project:
Listing 38-6
1
2
Don't forget to replace the values enclosed by < and > with your custom settings displayed in the
Deployment tab of your Azure Website panel. The git remote command connects the Azure Website
remote Git repository and assigns an alias to it with the name azure. The second git push command
pushes all your commits to the remote master branch of your remote azure Git repository.
The deployment with Git should produce an output similar to the screenshot below:
The code of the Symfony application has now been deployed to the Azure Website which you can browse
from the file explorer of the Kudu application. You should see the app/, src/ and web/ directories
under your site/wwwroot directory on the Azure Website filesystem.
1
2
3
$ cd site\wwwroot
$ curl -sS https://getcomposer.org/installer | php
$ php -d extension=php_intl.dll composer.phar install
The curl command retrieves and downloads the Composer command line tool and installs it at the
root of the site/wwwroot directory. Then, running the Composer install command downloads and
installs all necessary third-party libraries.
This may take a while depending on the number of third-party dependencies you've configured in your
composer.json file.
The -d switch allows you to quickly override/add any php.ini settings. In this command, we are
forcing PHP to use the intl extension, because it is not enabled by default in Azure Website at
the moment. Soon, this -d option will no longer be needed since Microsoft will enable the intl
extension by default.
At the end of the composer install command, you will be prompted to fill in the values of some
Symfony settings like database credentials, locale, mailer credentials, CSRF token protection, etc. These
parameters come from the app/config/parameters.yml.dist file.
The most important thing in this cookbook is to correctly set up your database settings. You can get your
MySQL database settings on the right sidebar of the Azure Website Dashboard panel. Simply click on
the View Connection Strings link to make them appear in a pop-in.
The displayed MySQL database settings should be something similar to the code below. Of course, each
value depends on what you've already configured.
Listing 38-8
Switch back to the console and answer the prompted questions and provide the following answers. Don't
forget to adapt the values below with your real values from the MySQL connection string.
Listing 38-9
1
2
3
4
5
6
7
database_driver: pdo_mysql
database_host: u-cdbr-azure-north-c.cloudapp.net
database_port: null
database_name: mysymfonyMySQL
database_user: bff2481a5b6074
database_password: bdf50b42
// ...
Don't forget to answer all the questions. It's important to set a unique random string for the secret
variable. For the mailer configuration, Azure Website doesn't provide a built-in mailer service. You
PDF brought to you by
generated on July 28, 2016
should consider configuring the host-name and credentials of some other third-party mailing service if
your application needs to send emails.
Your Symfony application is now configured and should be almost operational. The final step is to build
the database schema. This can easily be done with the command line interface if you're using Doctrine.
In the online Console tool of the Kudu application, run the following command to mount the tables into
your MySQL database.
Listing 38-10
This command builds the tables and indexes for your MySQL database. If your Symfony application is
more complex than a basic Symfony Standard Edition, you may have additional commands to execute
for setup (see How to Deploy a Symfony Application).
Make sure that your application is running by browsing the app.php front controller with your web
browser and the following URL:
Listing 38-11
http://<your-website-name>.azurewebsites.net/web/app.php
If Symfony is correctly installed, you should see the front page of your Symfony application showing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<rules>
<clear />
<rule name="BlockAccessToPublic" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{URL}" pattern="/web/*" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied."
statusDescription="You do not have permission to view this directory or page using the credentials that you
supplied." />
</rule>
<rule name="RewriteAssetsToPublic" stopProcessing="true">
<match url="^(.*)(\.css|\.js|\.jpg|\.png|\.gif)$" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
</conditions>
<action type="Rewrite" url="web/{R:0}" />
</rule>
<rule name="RewriteRequestsToPublic" stopProcessing="true">
<match url="^(.*)$" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
</conditions>
<action type="Rewrite" url="web/app.php/{R:0}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
As you can see, the latest rule RewriteRequestsToPublic is responsible for rewriting any URLs to
the web/app.php front controller which allows you to skip the web/ folder in the URL. The first rule
called BlockAccessToPublic matches all URL patterns that contain the web/ folder and serves a 403
Forbidden HTTP response instead. This example is based on Benjamin Eberlei's sample you can find
on GitHub in the SymfonyAzureEdition7 bundle.
Deploy this file under the site/wwwroot directory of the Azure Website and browse to your application
without the web/app.php segment in the URL.
Conclusion
Nice work! You've now deployed your Symfony application to the Microsoft Azure Website Cloud
platform. You also saw that Symfony can be easily configured and executed on a Microsoft IIS web server.
The process is simple and easy to implement. And as a bonus, Microsoft is continuing to reduce the
number of steps needed so that deployment becomes even easier.
7. https://github.com/beberlei/symfony-azure-edition/
Chapter 39
Setting up
To set up a new Heroku website, first sign up with Heroku2 or sign in with your credentials. Then
download and install the Heroku Toolbelt3 on your local computer.
You can also check out the getting Started with PHP on Heroku4 guide to gain more familiarity with the
specifics of working with PHP applications on Heroku.
1
2
# app/config/config_prod.yml
monolog:
1. https://devcenter.heroku.com/articles/getting-started-with-symfony2
2. https://signup.heroku.com/signup/dc
3. https://devcenter.heroku.com/articles/getting-started-with-php#set-up
4. https://devcenter.heroku.com/articles/getting-started-with-php
5. https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem
6. https://devcenter.heroku.com/articles/logplex
3
4
5
6
7
8
# ...
handlers:
# ...
nested:
# ...
path: 'php://stderr'
Once the application is deployed, run heroku logs --tail to keep the stream of logs from Heroku
open in your terminal.
1
2
3
4
5
$ heroku create
Creating mighty-hamlet-1981 in organization heroku... done, stack is cedar
http://mighty-hamlet-1981.herokuapp.com/ | [email protected]:mighty-hamlet-1981.git
Git remote heroku added
You are now ready to deploy the application as explained in the next section.
1) Create a Procfile
By default, Heroku will launch an Apache web server together with PHP to serve applications. However,
two special circumstances apply to Symfony applications:
1. The document root is in the web/ directory and not in the root directory of the application;
2. The Composer bin-dir, where vendor binaries (and thus Heroku's own boot scripts) are placed,
is bin/ , and not the default vendor/bin.
Vendor binaries are usually installed to vendor/bin by Composer, but sometimes (e.g. when
running a Symfony Standard Edition project!), the location will be different. If in doubt, you can
always run composer config bin-dir to figure out the right location.
Create a new file called Procfile (without any extension) at the root directory of the application and
add just the following content:
Listing 39-3
If you prefer to use Nginx, which is also available on Heroku, you can create a configuration file for
it and point to it from your Procfile as described in the Heroku documentation7:
Listing 39-4
7. https://devcenter.heroku.com/articles/custom-php-settings#nginx
If you prefer working on the command console, execute the following commands to create the
Procfile file and to add it to the repository:
Listing 39-5
1
2
3
4
5
Be aware that dependencies from composer.json listed in the require-dev section are never
installed during a deploy on Heroku. This may cause problems if your Symfony environment relies
on such packages. The solution is to move these packages from require-dev to the require
section.
1
2
3
In this case, you need to confirm by typing yes and hitting <Enter> key - ideally after you've verified
that the RSA key fingerprint is correct10.
Then, deploy your application executing this command:
Listing 39-8
1
2
3
4
5
6
7
8
9
10
8. https://getcomposer.org/doc/articles/scripts.md
9. https://devcenter.heroku.com/articles/config-vars
10. https://devcenter.heroku.com/articles/git-repository-ssh-fingerprints
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
And that's it! If you now open your browser, either by manually pointing it to the URL heroku create
gave you, or by using the Heroku Toolbelt, the application will respond:
Listing 39-9
1
2
$ heroku open
Opening mighty-hamlet-1981... done
11. https://devcenter.heroku.com/articles/php-support#custom-compile-step
12. https://getcomposer.org/doc/articles/scripts.md
13. https://getcomposer.org/doc/articles/scripts.md#writing-custom-commands
to the scripts section of your composer.json. The listed commands hook into Heroku's deploy
process:
Listing 39-10
1
2
3
4
5
6
7
{
"scripts": {
"compile": [
"rm web/app_dev.php"
]
}
}
This is also very useful to build assets on the production system, e.g. with Assetic:
Listing 39-11
1
2
3
4
5
6
7
{
"scripts": {
"compile": [
"app/console assetic:dump"
]
}
}
Node.js Dependencies
Building assets may depend on node packages, e.g. uglifyjs or uglifycss for asset minification.
Installing node packages during the deploy requires a node installation. But currently, Heroku
compiles your app using the PHP buildpack, which is auto-detected by the presence of a
composer.json file, and does not include a node installation. Because the Node.js buildpack has
a higher precedence than the PHP buildpack (see Heroku buildpacks14), adding a package.json
listing your node dependencies makes Heroku opt for the Node.js buildpack instead:
Listing 39-12
1
2
3
4
5
6
7
8
9
10
{
"name": "myApp",
"engines": {
"node": "0.12.x"
},
"dependencies": {
"uglifycss": "*",
"uglify-js": "*"
}
}
With the next deploy, Heroku compiles your app using the Node.js buildpack and your npm
packages become installed. On the other hand, your composer.json is now ignored. To compile
your app with both buildpacks, Node.js and PHP, you need to use both buildpacks. To override
buildpack auto-detection, you need to explicitly set the buildpack:
Listing 39-13
1
2
3
4
5
6
7
8
With the next deploy, you can benefit from both buildpacks. This setup also enables your Heroku
environment to make use of node based automatic build tools like Grunt15 or gulp16.
14. https://devcenter.heroku.com/articles/buildpacks
15. http://gruntjs.com
16. http://gulpjs.com
Chapter 40
Deploying to Platform.sh
This step-by-step cookbook describes how to deploy a Symfony web application to Platform.sh1. You can
read more about using Symfony with Platform.sh on the official Platform.sh documentation2.
1
2
3
4
5
6
7
8
9
10
11
12
# .platform.app.yaml
# This file describes an application. You can have multiple applications
# in the same project.
# The name of this app. Must be unique within a project.
name: myphpproject
# The type of the application to build.
type: php:5.6
build:
flavor: symfony
1. https://platform.sh
2. https://docs.platform.sh/toolstacks/symfony/symfony-getting-started
3. https://marketplace.commerceguys.com/platform/buy-now
4. https://docs.platform.sh/reference/configuration-files
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
For best practices, you should also add a .platform folder at the root of your Git repository which
contains the following files:
Listing 40-2
1
2
3
4
5
# .platform/routes.yaml
"http://{default}/":
type: upstream
# the first part should be your project name
upstream: 'myphpproject:php'
Listing 40-3
1
2
3
4
# .platform/services.yaml
mysql:
type: mysql
disk: 2048
An example of these configurations can be found on GitHub5. The list of available services6 can be found
on the Platform.sh documentation.
1
2
3
4
5
6
7
8
9
// app/config/parameters_platform.php
<?php
$relationships = getenv("PLATFORM_RELATIONSHIPS");
if (!$relationships) {
return;
}
$relationships = json_decode(base64_decode($relationships), true);
5. https://github.com/platformsh/platformsh-examples
6. https://docs.platform.sh/reference/configuration-files/#configure-services
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1
2
3
# app/config/config.yml
imports:
- { resource: parameters_platform.php }
PROJECT-ID
1
2
3
That's it! Your application is being deployed on Platform.sh and you'll soon be able to access it in your
browser.
Every code change that you do from now on will be pushed to Git in order to redeploy your environment
on Platform.sh.
More information about migrating your database and files7 can be found on the Platform.sh
documentation.
7. https://docs.platform.sh/toolstacks/php/symfony/migrate-existing-site/
8. https://marketplace.commerceguys.com/platform/buy-now
Chapter 41
Deploying to fortrabbit
This step-by-step cookbook describes how to deploy a Symfony web application to fortrabbit1. You can
read more about using Symfony with fortrabbit on the official fortrabbit Symfony install guide2.
Setting up fortrabbit
Before getting started, you should have done a few things on the fortrabbit side:
Sign up3;
Add an SSH key to your Account (to deploy via Git);
Create an App.
Configure Logging
Per default Symfony logs to a file. Modify the app/config/config_prod.yml file to redirect it to
error_log4:
Listing 41-1
1
2
3
4
5
6
# app/config/config_prod.yml
monolog:
# ...
handlers:
nested:
type: error_log
1. https://www.fortrabbit.com
2. https://help.fortrabbit.com/install-symfony
3. https://dashboard.fortrabbit.com
4. http://php.net/manual/en/function.error-log.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Make sure this file is imported into the main config file:
Listing 41-3
1
2
3
4
5
6
7
8
9
10
11
# app/config/config_prod.yml
imports:
- { resource: config.yml }
- { resource: config_prod_secrets.php }
# ..
framework:
session:
# set handler_id to null to use default session handler from php.ini (memcached)
handler_id: ~
# ..
Environment Variables
Set the SYMFONY_ENV environment variable to prod to make sure the right config files get loaded. ENV
vars are configuable in fortrabbit Dashboard as well.
Document Root
The document root is configuable for every custom domain you setup for your App. The default is
/htdocs, but for Symfony you probably want to change it to /htdocs/web. You also do so in the
fortrabbit Dashboard under Domain settings.
Deploying to fortrabbit
It is assumed that your codebase is under version-control with Git and dependencies are managed with
Composer (locally).
Every time you push to fortrabbit composer install runs before your code gets deployed. To finetune the
deployment behavior put a fortrabbit.yml5. deployment file (optional) in the project root.
Add fortrabbit as a (additional) Git remote and add your configuration changes:
Listing 41-4
1
2
3
1
2
Listing 41-6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
B U I L D
Checksum:
def1bb29911a62de26b1ddac6ef97fc76a5c647b
Deployment file:
fortrabbit.yml
Pre-script:
not found
0ms
Composer:
- - Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
5. https://help.fortrabbit.com/deployment-file-v2
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
- - 172ms
Post-script:
not found
0ms
R E L E A S E
Packaging:
930ms
Revision:
1455788127289043421.def1bb29911a62de26b1ddac6ef97fc76a5c647b
Size:
9.7MB
Uploading:
500ms
Build & release done in 1625ms, now queued for final distribution.
The first git push takes much longer as all composer dependencies get downloaded. All
subsequent deploys are done within seconds.
That's it! Your application is being deployed on fortrabbit. More information about database migrations
and tunneling6 can be found in the fortrabbit documentation.
6. https://help.fortrabbit.com/install-symfony-2#toc-migrate-amp-other-database-commands
Chapter 42
1. https://github.com/Atlantic18/DoctrineExtensions
2. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/sluggable.md
3. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/translatable.md
4. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md
5. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/loggable.md
6. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/tree.md
7. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/sortable.md
8. https://github.com/stof/StofDoctrineExtensionsBundle
9. https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/symfony2.md
Chapter 42: How to use Doctrine Extensions: Timestampable, Sluggable, Translatable, etc. | 160
Chapter 43
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_sqlite
memory: true
services:
my.listener:
class: AppBundle\EventListener\SearchIndexer
tags:
- { name: doctrine.event_listener, event: postPersist }
my.listener2:
class: AppBundle\EventListener\SearchIndexer2
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html
16
17
18
19
20
21
tags:
- { name: doctrine.event_listener, event: postPersist, connection: default }
my.subscriber:
class: AppBundle\EventListener\SearchIndexerSubscriber
tags:
- { name: doctrine.event_subscriber, connection: default }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/EventListener/SearchIndexer.php
namespace AppBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\Product;
class SearchIndexer
{
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
In each event, you have access to a LifecycleEventArgs object, which gives you access to both the
entity object of the event and the entity manager itself.
One important thing to notice is that a listener will be listening for all entities in your application. So, if
you're interested in only handling a specific type of entity (e.g. a Product entity but not a BlogPost
entity), you should check for the entity's class type in your method (as shown above).
In Doctrine 2.4, a feature called Entity Listeners was introduced. It is a lifecycle listener class used
for an entity. You can read about it in the Doctrine Documentation2.
1
2
3
4
5
// src/AppBundle/EventListener/SearchIndexerSubscriber.php
namespace AppBundle\EventListener;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
2. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Doctrine event subscribers can not return a flexible array of methods to call for the events like the
Symfony event subscriber can. Doctrine event subscribers must return a simple array of the event
names they subscribe to. Doctrine will then expect methods on the subscriber with the same name
as each subscribed event, just as when using an event listener.
For a full reference, see chapter The Event System3 in the Doctrine documentation.
3. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html
Chapter 44
This article is about the Doctrine DBAL. Typically, you'll work with the higher level Doctrine ORM
layer, which simply uses the DBAL behind the scenes to actually communicate with the database.
To read more about the Doctrine ORM, see "Databases and Doctrine".
The Doctrine1 Database Abstraction Layer (DBAL) is an abstraction layer that sits on top of PDO2 and
offers an intuitive and flexible API for communicating with the most popular relational databases. In
other words, the DBAL library makes it easy to execute queries and perform other database actions.
Read the official Doctrine DBAL Documentation3 to learn all the details and capabilities of Doctrine's
DBAL library.
# app/config/config.yml
doctrine:
dbal:
driver:
pdo_mysql
dbname:
Symfony
user:
root
password: null
charset: UTF8
server_version: 5.6
1
2
3
4
5
6
7
8
9
For full DBAL configuration options, or to learn how to configure multiple connections, see Doctrine
DBAL Configuration.
You can then access the Doctrine DBAL connection by accessing the database_connection service:
Listing 44-2
1
2
3
1. http://www.doctrine-project.org
2. http://www.php.net/pdo
3. http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/index.html
4
5
6
7
8
9
10
{
$conn = $this->get('database_connection');
$users = $conn->fetchAll('SELECT * FROM users');
// ...
}
}
1
2
3
4
5
6
# app/config/config.yml
doctrine:
dbal:
types:
custom_first: AppBundle\Type\CustomFirst
custom_second: AppBundle\Type\CustomSecond
1
2
3
4
5
# app/config/config.yml
doctrine:
dbal:
mapping_types:
enum: string
4. http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#custom-mapping-types
Chapter 45
This tutorial assumes you're using a simple blog application with the following two tables: blog_post
and blog_comment. A comment record is linked to a post record thanks to a foreign key constraint.
Listing 45-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/tools.html#reverse-engineering
17
18
CONSTRAINT `blog_post_id` FOREIGN KEY (`post_id`) REFERENCES `blog_post` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Before diving into the recipe, be sure your database connection parameters are correctly setup in the
app/config/parameters.yml file (or wherever your database configuration is kept) and that you
have initialized a bundle that will host your future entity class. In this tutorial it's assumed that an
AcmeBlogBundle exists and is located under the src/Acme/BlogBundle folder.
The first step towards building entity classes from an existing database is to ask Doctrine to introspect
the database and generate the corresponding metadata files. Metadata files describe the entity class to
generate based on table fields.
Listing 45-2
This command line tool asks Doctrine to introspect the database and generate the XML metadata
files under the src/Acme/BlogBundle/Resources/config/doctrine folder of your bundle. This
generates two files: BlogPost.orm.xml and BlogComment.orm.xml.
It's also possible to generate the metadata files in YAML format by changing the last argument to
yml.
1
2
3
4
5
6
7
8
9
10
11
Once the metadata files are generated, you can ask Doctrine to build related entity classes by executing
the following two commands.
Listing 45-4
1
2
The first command generates entity classes with annotation mappings. But if you want to use YAML or
XML mapping instead of annotations, you should execute the second command only.
If you want to use annotations, you must remove the XML (or YAML) files after running these two
commands. This is necessary as it is not possible to mix mapping configuration formats
For example, the newly created BlogComment entity class looks as follow:
Listing 45-5
1
2
3
4
5
6
// src/Acme/BlogBundle/Entity/BlogComment.php
namespace Acme\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
* Acme\BlogBundle\Entity\BlogComment
*
* @ORM\Table(name="blog_comment")
* @ORM\Entity
*/
class BlogComment
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="bigint")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $author
*
* @ORM\Column(name="author", type="string", length=100, nullable=false)
*/
private $author;
/**
* @var text $content
*
* @ORM\Column(name="content", type="text", nullable=false)
*/
private $content;
/**
* @var datetime $createdAt
*
* @ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private $createdAt;
/**
* @var BlogPost
*
* @ORM\ManyToOne(targetEntity="BlogPost")
* @ORM\JoinColumn(name="post_id", referencedColumnName="id")
*/
private $post;
}
As you can see, Doctrine converts all table fields to pure private and annotated class properties. The most
impressive thing is that it also discovered the relationship with the BlogPost entity class based on the
foreign key constraint. Consequently, you can find a private $post property mapped with a BlogPost
entity in the BlogComment entity class.
If you want to have a one-to-many relationship, you will need to add it manually into the entity or
to the generated XML or YAML files. Add a section on the specific entities for one-to-many defining
the inversedBy and the mappedBy pieces.
Chapter 46
The following configuration code shows how you can configure two entity managers:
Listing 46-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
doctrine:
dbal:
default_connection: default
connections:
default:
driver:
pdo_mysql
host:
'%database_host%'
port:
'%database_port%'
dbname:
'%database_name%'
user:
'%database_user%'
password: '%database_password%'
charset: UTF8
customer:
driver:
pdo_mysql
host:
'%database_host2%'
port:
'%database_port2%'
dbname:
'%database_name2%'
user:
'%database_user2%'
password: '%database_password2%'
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
Chapter 46: How to Work with multiple Entity Managers and Connections | 169
26
27
28
29
30
31
32
33
connection: default
mappings:
AppBundle: ~
AcmeStoreBundle: ~
customer:
connection: customer
mappings:
AcmeCustomerBundle: ~
In this case, you've defined two entity managers and called them default and customer. The
default entity manager manages entities in the AppBundle and AcmeStoreBundle, while the
customer entity manager manages entities in the AcmeCustomerBundle. You've also defined two
connections, one for each entity manager.
When working with multiple connections and entity managers, you should be explicit about which
configuration you want. If you do omit the name of the connection or entity manager, the default
(i.e. default) is used.
1
2
3
4
5
1
2
3
4
5
If you do omit the entity manager's name when asking for it, the default entity manager (i.e. default) is
returned:
Listing 46-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
You can now use Doctrine just as you did before - using the default entity manager to persist and fetch
entities that it manages and the customer entity manager to persist and fetch its entities.
The same applies to repository calls:
Listing 46-5
1
2
3
4
5
Chapter 46: How to Work with multiple Entity Managers and Connections | 170
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$products = $this->get('doctrine')
->getRepository('AcmeStoreBundle:Product')
->findAll()
;
Chapter 46: How to Work with multiple Entity Managers and Connections | 171
Chapter 47
1
2
3
4
5
6
7
8
9
10
11
12
# app/config/config.yml
doctrine:
orm:
# ...
dql:
string_functions:
test_string: AppBundle\DQL\StringFunction
second_string: AppBundle\DQL\SecondStringFunction
numeric_functions:
test_numeric: AppBundle\DQL\NumericFunction
datetime_functions:
test_datetime: AppBundle\DQL\DatetimeFunction
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html
Chapter 48
Background
Suppose you have an InvoiceBundle which provides invoicing functionality and a CustomerBundle that
contains customer management tools. You want to keep these separated, because they can be used in
other systems without each other, but for your application you want to use them together.
In this case, you have an Invoice entity with a relationship to a non-existent object, an
InvoiceSubjectInterface. The goal is to get the ResolveTargetEntityListener to replace
any mention of the interface with a real object that implements that interface.
Set up
This article uses the following two basic entities (which are incomplete for brevity) to explain how to set
up and use the ResolveTargetEntityListener.
A Customer entity:
Listing 48-1
Chapter 48: How to Define Relationships with Abstract Classes and Interfaces | 173
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/Acme/AppBundle/Entity/Customer.php
namespace Acme\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Acme\CustomerBundle\Entity\Customer as BaseCustomer;
use Acme\InvoiceBundle\Model\InvoiceSubjectInterface;
/**
* @ORM\Entity
* @ORM\Table(name="customer")
*/
class Customer extends BaseCustomer implements InvoiceSubjectInterface
{
// In this example, any methods defined in the InvoiceSubjectInterface
// are already implemented in the BaseCustomer
}
An Invoice entity:
Listing 48-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Acme/InvoiceBundle/Entity/Invoice.php
namespace Acme\InvoiceBundle\Entity;
use Doctrine\ORM\Mapping AS ORM;
use Acme\InvoiceBundle\Model\InvoiceSubjectInterface;
/**
* Represents an Invoice.
*
* @ORM\Entity
* @ORM\Table(name="invoice")
*/
class Invoice
{
/**
* @ORM\ManyToOne(targetEntity="Acme\InvoiceBundle\Model\InvoiceSubjectInterface")
* @var InvoiceSubjectInterface
*/
protected $subject;
}
An InvoiceSubjectInterface:
Listing 48-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/Acme/InvoiceBundle/Model/InvoiceSubjectInterface.php
namespace Acme\InvoiceBundle\Model;
/**
* An interface that the invoice Subject object should implement.
* In most circumstances, only a single object should implement
* this interface as the ResolveTargetEntityListener can only
* change the target to a single object.
*/
interface InvoiceSubjectInterface
{
// List any additional methods that your InvoiceBundle
// will need to access on the subject so that you can
// be sure that you have access to those methods.
/**
* @return string
*/
public function getName();
}
Next, you need to configure the listener, which tells the DoctrineBundle about the replacement:
Listing 48-4
Chapter 48: How to Define Relationships with Abstract Classes and Interfaces | 174
1
2
3
4
5
6
7
# app/config/config.yml
doctrine:
# ...
orm:
# ...
resolve_target_entities:
Acme\InvoiceBundle\Model\InvoiceSubjectInterface: Acme\AppBundle\Entity\Customer
Final Thoughts
With the ResolveTargetEntityListener, you are able to decouple your bundles, keeping them
usable by themselves, but still being able to define relationships between different objects. By using this
method, your bundles will end up being easier to maintain independently.
Chapter 48: How to Define Relationships with Abstract Classes and Interfaces | 175
Chapter 49
New in version 2.3: The base mapping compiler pass was introduced in Symfony 2.3. The Doctrine
bundles support it from DoctrineBundle >= 1.3.0, MongoDBBundle >= 3.0.0, PHPCRBundle >= 1.0.0
and the (unversioned) CouchDBBundle supports the compiler pass since the CouchDB Mapping
Compiler Pass pull request1 was merged.
New in version 2.6: Support for defining namespace aliases was introduced in Symfony 2.6. It is safe
to define the aliases with older versions of Symfony as the aliases are the last argument to
createXmlMappingDriver and are ignored by PHP if that argument doesn't exist.
In your bundle class, write the following code to register the compiler pass. This one is written for the
CmfRoutingBundle, so parts of it will need to be adapted for your case:
Listing 49-1
1
2
3
4
5
6
7
8
9
10
11
12
use
use
use
use
Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass;
Doctrine\Bundle\CouchDBBundle\DependencyInjection\Compiler\DoctrineCouchDBMappingsPass;
Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass;
1. https://github.com/doctrine/DoctrineCouchDBBundle/pull/27
Chapter 49: How to Provide Model Classes for several Doctrine Implementations | 176
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
$modelDir = realpath(__DIR__.'/Resources/config/doctrine/model');
$mappings = array(
$modelDir => 'Symfony\Cmf\RoutingBundle\Model',
);
$ormCompilerClass =
'Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass';
if (class_exists($ormCompilerClass)) {
$container->addCompilerPass(
DoctrineOrmMappingsPass::createXmlMappingDriver(
$mappings,
array('cmf_routing.model_manager_name'),
'cmf_routing.backend_type_orm',
array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model')
));
}
$mongoCompilerClass =
'Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass';
if (class_exists($mongoCompilerClass)) {
$container->addCompilerPass(
DoctrineMongoDBMappingsPass::createXmlMappingDriver(
$mappings,
array('cmf_routing.model_manager_name'),
'cmf_routing.backend_type_mongodb',
array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model')
));
}
$couchCompilerClass =
'Doctrine\Bundle\CouchDBBundle\DependencyInjection\Compiler\DoctrineCouchDBMappingsPass';
if (class_exists($couchCompilerClass)) {
$container->addCompilerPass(
DoctrineCouchDBMappingsPass::createXmlMappingDriver(
$mappings,
array('cmf_routing.model_manager_name'),
'cmf_routing.backend_type_couchdb',
array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model')
));
}
$phpcrCompilerClass =
'Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass';
if (class_exists($phpcrCompilerClass)) {
$container->addCompilerPass(
DoctrinePhpcrMappingsPass::createXmlMappingDriver(
$mappings,
array('cmf_routing.model_manager_name'),
'cmf_routing.backend_type_phpcr',
array('CmfRoutingBundle' => 'Symfony\Cmf\RoutingBundle\Model')
));
}
}
}
Note the class_exists2 check. This is crucial, as you do not want your bundle to have a hard
dependency on all Doctrine bundles but let the user decide which to use.
The compiler pass provides factory methods for all drivers provided by Doctrine: Annotations, XML,
Yaml, PHP and StaticPHP. The arguments are:
A map/hash of absolute directory path to namespace;
An array of container parameters that your bundle uses to specify the name of the Doctrine manager
that it is using. In the example above, the CmfRoutingBundle stores the manager name that's being
used under the cmf_routing.model_manager_name parameter. The compiler pass will append the parameter
2. http://php.net/manual/en/function.class-exists.php
Chapter 49: How to Provide Model Classes for several Doctrine Implementations | 177
Doctrine is using to specify the name of the default manager. The first parameter found is used and
the mappings are registered with that manager;
An optional container parameter name that will be used by the compiler pass to determine if this
Doctrine type is used at all. This is relevant if your user has more than one type of Doctrine bundle
installed, but your bundle is only used with one type of Doctrine;
A map/hash of aliases to namespace. This should be the same convention used by Doctrine automapping. In the example above, this allows the user to call $om->getRepository('CmfRoutingBundle:Route').
The factory method is using the SymfonyFileLocator of Doctrine, meaning it will only see XML
and YML mapping files if they do not contain the full namespace as the filename. This is by design:
the SymfonyFileLocator simplifies things by assuming the files are just the "short" version of the
class as their filename (e.g. BlogPost.orm.xml)
If you also need to map a base class, you can register a compiler pass with the
DefaultFileLocator like this. This code is taken from the DoctrineOrmMappingsPass and
adapted to use the DefaultFileLocator instead of the SymfonyFileLocator:
Listing 49-2
1
2
3
4
5
6
7
8
9
10
11
12
13
Note that you do not need to provide a namespace alias unless your users are expected to ask
Doctrine for the base classes.
Now place your mapping file into /Resources/config/doctrine-base with the fully qualified
class name, separated by . instead of \, for example Other.Namespace.Model.Name.orm.xml.
You may not mix the two as otherwise the SymfonyFileLocator will get confused.
Adjust accordingly for the other Doctrine implementations.
Chapter 49: How to Provide Model Classes for several Doctrine Implementations | 178
Chapter 50
If you don't already have a User entity and a working login system, first start with How to Load Security
Users from the Database (the Entity Provider).
Your User entity will probably at least have the following fields:
username
This will be used for logging in, unless you instead want your user to login via email (in that case,
this field is unnecessary).
email
A nice piece of information to collect. You can also allow users to login via email.
password
This field is not persisted: (notice no @ORM\Column above it). It temporarily stores the plain password
from the registration form. This field can be validated and is then used to populate the password field.
With some validation added, your class may look something like this:
Listing 50-1
1
2
3
4
5
6
7
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use
use
use
use
Doctrine\ORM\Mapping as ORM;
Symfony\Component\Validator\Constraints as Assert;
Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
Symfony\Component\Security\Core\User\UserInterface;
1. https://github.com/FriendsOfSymfony/FOSUserBundle
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @ORM\Entity
* @UniqueEntity(fields="email", message="Email already taken")
* @UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank()
*/
private $username;
/**
* @Assert\NotBlank()
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
* The below length depends on the "algorithm" you use for encoding
* the password, but this works well with bcrypt.
*
* @ORM\Column(type="string", length=64)
*/
private $password;
// other properties and methods
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
$this->plainPassword = $password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
The UserInterface2 requires a few other methods and your security.yml file needs to be
configured properly to work with the User entity. For a more complete example, see the Entity Provider
article.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/AppBundle/Form/UserType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email')
->add('username', 'text')
->add('plainPassword', 'repeated', array(
'type' => 'password',
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
)
);
}
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html
3. https://symfony.com/blog/cve-2013-5750-security-issue-in-fosuserbundle-login-form
23
24
25
26
27
28
29
30
31
32
33
34
There are just three fields: email, username and plainPassword (repeated to confirm the entered
password).
To explore more things about the Form component, read the chapter about forms in the book.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// src/AppBundle/Controller/RegistrationController.php
namespace AppBundle\Controller;
use
use
use
use
use
AppBundle\Form\UserType;
AppBundle\Entity\User;
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
Symfony\Bundle\FrameworkBundle\Controller\Controller;
Symfony\Component\HttpFoundation\Request;
40
41
42
43
44
45
46
return $this->render(
'registration/register.html.twig',
array('form' => $form->createView())
);
}
}
To define the algorithm used to encode the password in step 3 configure the encoder in the security
configuration:
Listing 50-4
# app/config/security.yml
security:
encoders:
AppBundle\Entity\User: bcrypt
1
2
3
4
In this case the recommended bcrypt algorithm is used. To learn more about how to encode the users
password have a look into the security chapter.
If you decide to NOT use annotation routing (shown above), then you'll need to create a route to
this controller:
Listing 50-5
1
2
3
4
# app/config/routing.yml
user_registration:
path:
/register
defaults: { _controller: AppBundle:Registration:register }
1
2
3
4
5
6
7
8
9
10
{# app/Resources/views/registration/register.html.twig #}
{{ form_start(form) }}
{{ form_row(form.username) }}
{{ form_row(form.email) }}
{{ form_row(form.plainPassword.first) }}
{{ form_row(form.plainPassword.second) }}
<button type="submit">Register!</button>
{{ form_end(form) }}
Listing 50-8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/AppBundle/Entity/User.php
// ...
class User implements UserInterface
{
// ...
public function getUsername()
{
return $this->email;
}
// ...
}
Next, just update the providers section of your security.yml file so that Symfony knows how to
load your users via the email property on login. See Using a Custom Query to Load the User.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Form/UserType.php
// ...
use Symfony\Component\Validator\Constraints\IsTrue;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email');
// ...
->add('termsAccepted', 'checkbox', array(
'mapped' => false,
'constraints' => new IsTrue(),
))
);
}
}
The constraints option is also used, which allows us to add validation, even though there is no
termsAccepted property on User.
Chapter 51
There was a backwards-compatibility break in Symfony 2.6: the database schema changed slightly.
See Symfony 2.6 Changes for details.
The default Symfony session storage writes the session information to files. Most medium to large
websites use a database to store the session values instead of files, because databases are easier to use and
scale in a multiple web server environment.
Symfony has a built-in solution for database session storage called PdoSessionHandler1. To use it,
you just need to change some parameters in the main configuration file:
Listing 51-1
1
2
3
4
5
6
7
8
9
10
11
12
13
# app/config/config.yml
framework:
session:
# ...
handler_id: session.handler.pdo
services:
session.handler.pdo:
class:
Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
public:
false
arguments:
- 'mysql:dbname=mydatabase'
- { db_username: myuser, db_password: mypassword }
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.html
Chapter 51: How to Use PdoSessionHandler to Store Sessions in the Database | 185
Listing 51-2
1
2
3
4
5
6
7
8
9
# app/config/config.yml
services:
# ...
session.handler.pdo:
class:
Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
public:
false
arguments:
- 'mysql:dbname=mydatabase'
- { db_table: sessions, db_username: myuser, db_password: mypassword }
New in version 2.6: The db_lifetime_col was introduced in Symfony 2.6. Prior to 2.6, this column
did not exist.
These are parameters that you must configure:
db_table (default sessions):
The name of the session table in your database;
db_id_col (default sess_id):
1
2
3
4
5
6
7
services:
session.handler.pdo:
class:
Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
public:
false
arguments:
- 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%'
- { db_username: '%database_user%', db_password: '%database_password%' }
Chapter 51: How to Use PdoSessionHandler to Store Sessions in the Database | 186
MySQL
Listing 51-4
1
2
3
4
5
6
A BLOB column type can only store up to 64 kb. If the data stored in a user's session exceeds this, an
exception may be thrown or their session will be silently reset. Consider using a MEDIUMBLOB if you
need more space.
PostgreSQL
Listing 51-5
1
2
3
4
5
6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Chapter 51: How to Use PdoSessionHandler to Store Sessions in the Database | 187
If the session data doesn't fit in the data column, it might get truncated by the database engine. To
make matters worse, when the session data gets corrupted, PHP ignores the data without giving a
warning.
If the application stores large amounts of session data, this problem can be solved by increasing the
column size (use BLOB or even MEDIUMBLOB). When using MySQL as the database engine, you can
also enable the strict SQL mode2 to get noticed when such an error happens.
2. https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
Chapter 51: How to Use PdoSessionHandler to Store Sessions in the Database | 188
Chapter 52
has
built-in
solution
for
NoSQL
database
session
storage
called
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# app/config/config.yml
framework:
session:
# ...
handler_id: session.handler.mongo
cookie_lifetime: 2592000 # optional, it is set to 30 days here
gc_maxlifetime: 2592000 # optional, it is set to 30 days here
services:
# ...
mongo_client:
class: MongoClient
# if using a username and password
arguments: ['mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017']
# if not using a username and password
arguments: ['mongodb://%mongodb_host%:27017']
session.handler.mongo:
class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler
arguments: ['@mongo_client', '%mongo.session.options%']
The parameters used above should be defined somewhere in your application, often in your main
parameters configuration:
Listing 52-2
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.html
2. http://docs.mongodb.org/manual/installation/
Chapter 52: How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database | 189
1
2
3
4
5
6
7
8
9
# app/config/parameters.yml
parameters:
# ...
mongo.session.options:
database: session_db # your MongoDB database name
collection: session # your MongoDB collection name
mongodb_host: 1.2.3.4 # your MongoDB server's IP
mongodb_username: my_username
mongodb_password: my_password
1
2
use session_db
db.session.ensureIndex( { "expires_at": 1 }, { expireAfterSeconds: 0 } )
3. http://docs.mongodb.org/v2.2/tutorial/getting-started-with-the-mongo-shell/
Chapter 52: How to Use MongoDbSessionHandler to Store Sessions in a MongoDB Database | 190
Chapter 53
Console Commands
The Doctrine2 ORM integration offers several console commands under the doctrine namespace. To
view the command list you can use the list command:
Listing 53-1
A list of available commands will print out. You can find out more information about any of these
commands (or any Symfony command) by running the help command. For example, to get details
about the doctrine:database:create task, run:
Listing 53-2
Chapter 54
Configuration
To use Swift Mailer, you'll need to configure it for your mail server.
Instead of setting up/using your own mail server, you may want to use a hosted mail provider such
as Mandrill2, SendGrid3, Amazon SES4 or others. These give you an SMTP server, username and
password (sometimes called keys) that can be used with the Swift Mailer configuration.
1
2
3
4
5
6
# app/config/config.yml
swiftmailer:
transport: '%mailer_transport%'
host:
'%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
These values (e.g. %mailer_transport%), are reading from the parameters that are set in the
parameters.yml file. You can modify the values in that file, or set the values directly here.
The following configuration attributes are available:
1.
2.
3.
4.
or gmail)
username
password
http://swiftmailer.org/
https://mandrill.com/
https://sendgrid.com/
http://aws.amazon.com/ses/
host
port
encryption (tls,
or ssl)
or cram-md5)
spool
type
path
(how to queue the messages, file or memory is supported, see How to Spool Emails)
(where to store the messages)
delivery_address
disable_delivery
Sending Emails
The Swift Mailer library works by creating, configuring and then sending Swift_Message objects. The
"mailer" is responsible for the actual delivery of the message and is accessible via the mailer service.
Overall, sending an email is pretty straightforward:
Listing 54-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
To keep things decoupled, the email body has been stored in a template and rendered with the
renderView() method. The registration.html.twig template might look something like this:
Listing 54-3
1
2
3
4
5
6
7
8
9
10
11
12
{# app/Resources/views/Emails/registration.html.twig #}
<h3>You did it! You registered!</h3>
Hi {{ name }}! You're successfully registered.
New in version 2.7: The absolute_url() function was introduced in Symfony 2.7. Prior to 2.7, the
asset() function has an argument to enable returning an absolute URL.
The $message object supports many more options, such as including attachments, adding HTML
content, and much more. Fortunately, Swift Mailer covers the topic of Creating Messages5 in great detail
in its documentation.
Several other cookbook articles are available related to sending emails in Symfony:
How to Use Gmail to Send Emails
How to Work with Emails during Development
How to Spool Emails
5. http://swiftmailer.org/docs/messages.html
Chapter 55
1
2
3
4
5
# app/config/config_dev.yml
swiftmailer:
transport: gmail
username: your_gmail_username
password: your_gmail_password
Listing 55-3
1
2
3
4
5
# app/config/parameters.yml
parameters:
# ...
mailer_user:
your_gmail_username
mailer_password: your_gmail_password
1
2
3
4
5
# app/config/config_dev.yml
swiftmailer:
transport: gmail
username: '%mailer_user%'
password: '%mailer_password%'
Value
encryption
ssl
Option
Value
auth_mode
login
host
smtp.gmail.com
If your application uses tls encryption or oauth authentication, you must override the default options
by defining the encryption and auth_mode parameters.
If your Gmail account uses 2-Step-Verification, you must generate an App password1 and use it as the
value of the mailer_password parameter. You must also ensure that you allow less secure apps to
access your Gmail account2.
See the Swiftmailer configuration reference for more details.
1. https://support.google.com/accounts/answer/185833
2. https://support.google.com/accounts/answer/6010255
Chapter 56
In the Symfony configuration, change the Swift Mailer settings transport, host, port and
encryption according to the information provided in the SES console2. Create your individual SMTP
credentials in the SES console and complete the configuration with the provided username and
password:
Listing 56-1
1
2
3
4
5
6
7
8
# app/config/config.yml
swiftmailer:
transport: smtp
host:
email-smtp.us-east-1.amazonaws.com
port:
587 # different ports are available, see SES console
encryption: tls # TLS encryption is required
username:
AWS_SES_SMTP_USERNAME # to be created in the SES console
password:
AWS_SES_SMTP_PASSWORD # to be created in the SES console
The port and encryption keys are not present in the Symfony Standard Edition configuration by
default, but you can simply add them as needed.
And that's it, you're ready to start sending emails through the cloud!
1. http://aws.amazon.com/ses
2. https://console.aws.amazon.com/ses
If you are using the Symfony Standard Edition, configure the parameters in parameters.yml
and use them in your configuration files. This allows for different Swift Mailer configurations for
each installation of your application. For instance, use Gmail during development and the cloud in
production.
Listing 56-2
1
2
3
4
5
6
7
8
9
# app/config/parameters.yml
parameters:
# ...
mailer_transport: smtp
mailer_host:
email-smtp.us-east-1.amazonaws.com
mailer_port:
587 # different ports are available, see SES console
mailer_encryption: tls # TLS encryption is required
mailer_user:
AWS_SES_SMTP_USERNAME # to be created in the SES console
mailer_password:
AWS_SES_SMTP_PASSWORD # to be created in the SES console
3. http://aws.amazon.com
Chapter 57
Disabling Sending
You can disable sending email by setting the disable_delivery option to true. This is the default in
the test environment in the Standard distribution. If you do this in the test specific config then email
will not be sent when you run tests, but will continue to be sent in the prod and dev environments:
Listing 57-1
1
2
3
# app/config/config_test.yml
swiftmailer:
disable_delivery: true
If you'd also like to disable deliver in the dev environment, simply add this same configuration to the
config_dev.yml file.
1
2
3
# app/config/config_dev.yml
swiftmailer:
delivery_address: '[email protected]'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In the dev environment, the email will instead be sent to [email protected]. Swift Mailer will add
an extra header to the email, X-Swift-To, containing the replaced address, so you can still see who it
would have been sent to.
In addition to the to addresses, this will also stop the email being sent to any CC and BCC addresses
set for it. Swift Mailer will add additional headers to the email with the overridden addresses in them.
These are X-Swift-Cc and X-Swift-Bcc for the CC and BCC addresses respectively.
1
2
3
4
5
6
7
8
# app/config/config_dev.yml
swiftmailer:
delivery_address: [email protected]
delivery_whitelist:
# all email addresses matching these regexes will be delivered
# like normal, as well as being sent to [email protected]
- '/@specialdomain\.com$/'
- '/^admin@mydomain\.com$/'
In the above example all email messages will be redirected to [email protected] and messages sent
to the [email protected] address or to any email address belonging to the domain
specialdomain.com will also be delivered as normal.
Listing 57-5
1
2
3
# app/config/config_dev.yml
web_profiler:
intercept_redirects: true
Alternatively, you can open the profiler after the redirect and search by the submit URL used on
the previous request (e.g. /contact/handle). The profiler's search feature allows you to load the
profiler information for any past requests.
Chapter 58
1
2
3
4
# app/config/config.yml
swiftmailer:
# ...
spool: { type: memory }
1
2
3
# app/config/config.yml
swiftmailer:
# ...
4
5
6
spool:
type: file
path: /path/to/spooldir
If you want to store the spool somewhere with your project directory, remember that you can use
the %kernel.root_dir% parameter to reference the project's root:
Listing 58-3
path: '%kernel.root_dir%/spool'
Now, when your app sends an email, it will not actually be sent but instead added to the spool. Sending
the messages from the spool is done separately. There is a console command to send the messages in the
spool:
Listing 58-4
Of course you will not want to run this manually in reality. Instead, the console command should be
triggered by a cron job or scheduled task and run at a regular interval.
Chapter 59
1
2
3
4
5
6
7
8
9
10
11
12
13
Don't forget to enable the profiler as explained in How to Use the Profiler in a Functional Test.
In your functional test, use the swiftmailer collector on the profiler to get information about the
messages sent on the previous request:
Listing 59-2
1
2
3
4
// src/AppBundle/Tests/Controller/MailControllerTest.php
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MailControllerTest extends WebTestCase
1. http://swiftmailer.org/
Chapter 59: How to Test that an Email is Sent in a Functional Test | 204
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
public function testMailIsSentAndContentIsOk()
{
$client = static::createClient();
// Enable the profiler for the next request (it does nothing if the profiler is not available)
$client->enableProfiler();
$crawler = $client->request('POST', '/path/to/above/action');
$mailCollector = $client->getProfile()->getCollector('swiftmailer');
Chapter 59: How to Test that an Email is Sent in a Functional Test | 205
Chapter 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/EventListener/ExceptionListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
$message = sprintf(
'My Error says: %s with code: %s',
$exception->getMessage(),
$exception->getCode()
);
1. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelEvents.html
24
25
26
27
28
29
30
31
32
33
34
35
36
Each event receives a slightly different type of $event object. For the kernel.exception event,
it is GetResponseForExceptionEvent2. To see what type of object each event listener receives,
see KernelEvents3 or the documentation about the specific event you're listening to.
Now that the class is created, you just need to register it as a service and notify Symfony that it is a
"listener" on the kernel.exception event by using a special "tag":
Listing 60-2
# app/config/services.yml
services:
app.exception_listener:
class: AppBundle\EventListener\ExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception }
1
2
3
4
5
6
There is an optional tag attribute called method which defines which method to execute when the
event is triggered. By default the name of the method is on + "camel-cased event name". If the event
is kernel.exception the method executed by default is onKernelException().
The other optional tag attribute is called priority, which defaults to 0 and it controls the order
in which listeners are executed (the highest the priority, the earlier a listener is executed). This is
useful when you need to guarantee that one listener is executed before another. The priorities of
the internal Symfony listeners usually range from -255 to 255 but your own listeners can use any
positive or negative integer.
1
2
// src/AppBundle/EventSubscriber/ExceptionSubscriber.php
namespace AppBundle\EventSubscriber;
2. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Event/GetResponseForExceptionEvent.html
3. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/KernelEvents.html
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return array(
KernelEvents::EXCEPTION => array(
array('processException', 10),
array('logException', 0),
array('notifyException', -10),
)
);
}
public function processException(GetResponseForExceptionEvent $event)
{
// ...
}
public function logException(GetResponseForExceptionEvent $event)
{
// ...
}
public function notifyException(GetResponseForExceptionEvent $event)
{
// ...
}
}
Now, you just need to register the class as a service and add the kernel.event_subscriber tag to
tell Symfony that this is an event subscriber:
Listing 60-4
1
2
3
4
5
6
# app/config/services.yml
services:
app.exception_subscriber:
class: AppBundle\EventSubscriber\ExceptionSubscriber
tags:
- { name: kernel.event_subscriber }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/AppBundle/EventListener/RequestListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class RequestListener
{
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
15
16
17
18
19
// ...
}
}
Certain things, like checking information on the real request, may not need to be done on the sub-request
listeners.
Listeners or Subscribers
Listeners and subscribers can be used in the same application indistinctly. The decision to use either of
them is usually a matter of personal taste. However, there are some minor advantages for each of them:
Subscribers are easier to reuse because the knowledge of the events is kept in the class rather than
in the service definition. This is the reason why Symfony uses subscribers internally;
Listeners are more flexible because bundles can enable or disable each of them conditionally
depending on some configuration value.
You can get registered listeners for a particular event by specifying its name:
Listing 60-7
Chapter 61
1
2
3
4
5
# app/config/config.yml
parameters:
tokens:
client1: pass1
client2: pass2
1
2
3
4
5
6
namespace AppBundle\Controller;
interface TokenAuthenticatedController
{
// ...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace AppBundle\Controller;
use AppBundle\Controller\TokenAuthenticatedController;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class FooController extends Controller implements TokenAuthenticatedController
{
// An action that needs authentication
public function barAction()
{
// ...
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// src/AppBundle/EventListener/TokenListener.php
namespace AppBundle\EventListener;
use AppBundle\Controller\TokenAuthenticatedController;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class TokenListener
{
private $tokens;
public function __construct($tokens)
{
$this->tokens = $tokens;
}
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
/*
* $controller passed can be either a class or a Closure.
* This is not usual in Symfony but it may happen.
* If it is a class, it comes in array format
*/
if (!is_array($controller)) {
return;
}
if ($controller[0] instanceof TokenAuthenticatedController) {
$token = $event->getRequest()->query->get('token');
32
33
34
35
36
37
if (!in_array($token, $this->tokens)) {
throw new AccessDeniedHttpException('This action needs a valid token!');
}
}
}
}
1
2
3
4
5
6
7
# app/config/services.yml
services:
app.tokens.action_listener:
class: AppBundle\EventListener\TokenListener
arguments: ['%tokens%']
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Now, add another method to this class - onKernelResponse - that looks for this flag on the request
object and sets a custom header on the response if it's found:
Listing 61-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Finally, a second "tag" is needed in the service definition to notify Symfony that the onKernelResponse
event should be notified for the kernel.response event:
Listing 61-8
1
2
3
4
5
6
7
8
# app/config/services.yml
services:
app.tokens.action_listener:
class: AppBundle\EventListener\TokenListener
arguments: ['%tokens%']
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
That's it! The TokenListener is now notified before every controller is executed
(onKernelController) and after every controller returns a response (onKernelResponse). By
making specific controllers implement the TokenAuthenticatedController interface, your listener
knows which controllers it should take action on. And by storing a value in the request's "attributes" bag,
the onKernelResponse method knows to add the extra header. Have fun!
Chapter 62
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Foo
{
// ...
public function __call($method, $arguments)
{
// create an event named 'foo.method_is_not_found'
$event = new HandleUndefinedMethodEvent($this, $method, $arguments);
$this->dispatcher->dispatch('foo.method_is_not_found', $event);
// no listener was able to process the event? The method does not exist
if (!$event->isProcessed()) {
throw new \Exception(sprintf('Call to undefined method %s::%s.', get_class($this), $method));
}
// return the listener returned value
return $event->getReturnValue();
}
}
This uses a special HandleUndefinedMethodEvent that should also be created. This is a generic class
that could be reused each time you need to use this pattern of class extension:
Listing 62-2
1
2
3
4
5
6
7
8
9
10
11
use Symfony\Component\EventDispatcher\Event;
class HandleUndefinedMethodEvent extends Event
{
protected $subject;
protected $method;
protected $arguments;
protected $returnValue;
protected $isProcessed = false;
public function __construct($subject, $method, $arguments)
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{
$this->subject = $subject;
$this->method = $method;
$this->arguments = $arguments;
}
public function getSubject()
{
return $this->subject;
}
public function getMethod()
{
return $this->method;
}
public function getArguments()
{
return $this->arguments;
}
/**
* Sets the value to return and stops other listeners from being notified
*/
public function setReturnValue($val)
{
$this->returnValue = $val;
$this->isProcessed = true;
$this->stopPropagation();
}
public function getReturnValue()
{
return $this->returnValue;
}
public function isProcessed()
{
return $this->isProcessed;
}
}
Next, create a class that will listen to the foo.method_is_not_found event and add the method
bar():
Listing 62-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Bar
{
public function onFooMethodIsNotFound(HandleUndefinedMethodEvent $event)
{
// only respond to the calls to the 'bar' method
if ('bar' != $event->getMethod()) {
// allow another listener to take care of this unknown method
return;
}
Finally, add the new bar method to the Foo class by registering an instance of Bar with the
foo.method_is_not_found event:
Listing 62-4
1
2
Chapter 63
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Foo
{
// ...
public function send($foo, $bar)
{
// do something before the method
$event = new FilterBeforeSendEvent($foo, $bar);
$this->dispatcher->dispatch('foo.pre_send', $event);
// get $foo and $bar from the event, they may have been modified
$foo = $event->getFoo();
$bar = $event->getBar();
// the real method implementation is here
$ret = ...;
// do something after the method
$event = new FilterSendReturnValue($ret);
$this->dispatcher->dispatch('foo.post_send', $event);
return $event->getReturnValue();
}
}
In this example, two events are thrown: foo.pre_send, before the method is executed, and
foo.post_send after the method is executed. Each uses a custom Event class to communicate
information to the listeners of the two events. These event classes would need to be created by you and
should allow, in this example, the variables $foo, $bar and $ret to be retrieved and set by the listeners.
PDF brought to you by
generated on July 28, 2016
Chapter 63: How to Customize a Method Behavior without Using Inheritance | 217
For example, assuming the FilterSendReturnValue has a setReturnValue method, one listener
might look like this:
Listing 63-2
1
2
3
4
5
6
7
Chapter 63: How to Customize a Method Behavior without Using Inheritance | 218
Chapter 64
Configuring services;
Route matching conditions;
Checking security (explained below) and access controls with allow_if;
Validation.
For more information about how to create and work with expressions, see The Expression Syntax.
1
2
3
4
5
6
7
8
9
10
11
use Symfony\Component\ExpressionLanguage\Expression;
// ...
public function indexAction()
{
$this->denyAccessUnlessGranted(new Expression(
'"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())'
));
// ...
}
In this example, if the current user has ROLE_ADMIN or if the current user object's isSuperAdmin()
method returns true, then access will be granted (note: your User object may not have an
isSuperAdmin method, that method is invented for this example).
1. http://api.symfony.com/2.7/Symfony/Component/ExpressionLanguage/Expression.html
Chapter 64: How to use Expressions in Security, Routing, Services, and Validation | 219
This uses an expression and you can learn more about the expression language syntax, see The Expression
Syntax.
Inside the expression, you have access to a number of variables:
user
The user object (or the string anon if you're not authenticated).
roles
The array of roles the user has, including from the role hierarchy but not including the
IS_AUTHENTICATED_* attributes (see the functions below).
object
The object (if any) that's passed as the second argument to isGranted.
token
The AuthenticationTrustResolverInterface2, object: you'll probably use the is_* functions below instead.
Additionally, you have access to a number of functions inside the expression:
is_authenticated
Returns true if the user is authenticated via "remember-me" or authenticated "fully" - i.e. returns true
if the user is "logged in".
is_anonymous
Checks to see if the user has the given role - equivalent to an expression like 'ROLE_ADMIN'
in roles.
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/AuthenticationTrustResolverInterface.html
Chapter 64: How to use Expressions in Security, Routing, Services, and Validation | 220
1
2
3
4
5
6
7
8
9
use Symfony\Component\ExpressionLanguage\Expression;
// ...
$ac = $this->get('security.authorization_checker');
$access1 = $ac->isGranted('IS_AUTHENTICATED_REMEMBERED');
$access2 = $ac->isGranted(new Expression(
'is_remember_me() or is_fully_authenticated()'
));
Here, $access1 and $access2 will be the same value. Unlike the behavior of
IS_AUTHENTICATED_REMEMBERED and IS_AUTHENTICATED_FULLY, the is_remember_me
function only returns true if the user is authenticated via a remember-me cookie and
is_fully_authenticated only returns true if the user has actually logged in during this session
(i.e. is full-fledged).
Chapter 64: How to use Expressions in Security, Routing, Services, and Validation | 221
Chapter 65
{{ form_row(form.age) }}
You can also render each of the three parts of the field individually:
Listing 65-2
1
2
3
4
5
<div>
{{ form_label(form.age) }}
{{ form_errors(form.age) }}
{{ form_widget(form.age) }}
</div>
In both cases, the form label, errors and HTML widget are rendered by using a set of markup that ships
standard with Symfony. For example, both of the above templates would render:
Listing 65-3
1
2
3
4
5
6
7
<div>
<label for="form_age">Age</label>
<ul>
<li>This field is required</li>
</ul>
<input type="number" id="form_age" name="form[age]" />
</div>
To quickly prototype and test a form, you can render the entire form with just one line:
Listing 65-4
1
2
3
4
5
{# renders all fields *and* the form start and end tags #}
{{ form(form) }}
The remainder of this recipe will explain how every part of the form's markup can be modified at
several different levels. For more information about form rendering in general, see Rendering a Form in a
Template.
In the next section you will learn how to customize a theme by overriding some or all of its fragments.
For example, when the widget of an integer type field is rendered, an input number field is generated
Listing 65-5
{{ form_widget(form.age) }}
renders:
Listing 65-6
Internally, Symfony uses the integer_widget fragment to render the field. This is because the field
type is integer and you're rendering its widget (as opposed to its label or errors).
In Twig that would default to the block integer_widget from the form_div_layout.html.twig6
template.
1. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
2. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_table_layout.html.twig
3. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig
4. http://getbootstrap.com/
5. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_horizontal_layout.html.twig
6. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
1
2
3
4
5
{# form_div_layout.html.twig #}
{% block integer_widget %}
{% set type = type|default('number') %}
{{ block('form_widget_simple') }}
{% endblock integer_widget %}
As you can see, this fragment itself renders another fragment - form_widget_simple:
Listing 65-8
1
2
3
4
5
{# form_div_layout.html.twig #}
{% block form_widget_simple %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}"
{% endif %}/>
{% endblock form_widget_simple %}
The point is, the fragments dictate the HTML output of each part of a form. To customize the form
output, you just need to identify and override the correct fragment. A set of these form fragment
customizations is known as a form "theme". When rendering a form, you can choose which form
theme(s) you want to apply.
In Twig a theme is a single template file and the fragments are the blocks defined in this file.
In PHP a theme is a folder and the fragments are individual template files in this folder.
Form Theming
To see the power of form theming, suppose you want to wrap every input number field with a div tag.
The key to doing this is to customize the integer_widget fragment.
Method
Pros
Cons
Both methods have the same effect but are better in different situations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{% extends 'base.html.twig' %}
{% form_theme form _self %}
{% block integer_widget %}
<div class="integer_widget">
{% set type = type|default('number') %}
{{ block('form_widget_simple') }}
</div>
{% endblock %}
{% block content %}
{# ... render the form #}
{{ form_row(form.age) }}
{% endblock %}
By using the special {% form_theme form _self %} tag, Twig looks inside the same template for
any overridden form blocks. Assuming the form.age field is an integer type field, when its widget is
rendered, the customized integer_widget block will be used.
The disadvantage of this method is that the customized form block can't be reused when rendering other
forms in other templates. In other words, this method is most useful when making form customizations
that are specific to a single form in your application. If you want to reuse a form customization across
several (or all) forms in your application, read on to the next section.
1
2
3
4
5
6
7
{# app/Resources/views/form/fields.html.twig #}
{% block integer_widget %}
<div class="integer_widget">
{% set type = type|default('number') %}
{{ block('form_widget_simple') }}
</div>
{% endblock %}
Now that you've created the customized form block, you need to tell Symfony to use it. Inside the
template where you're actually rendering your form, tell Symfony to use the template via the
form_theme tag:
Listing 65-11
1
2
3
When the form.age widget is rendered, Symfony will use the integer_widget block from the new
template and the input tag will be wrapped in the div element specified in the customized block.
Multiple Templates
A form can also be customized by applying several templates. To do this, pass the name of all the
templates as an array using the with keyword:
Listing 65-12
1
2
3
{# ... #}
The templates can also be located in different bundles, use the functional name to reference these
templates, e.g. AcmeFormExtraBundle:form:fields.html.twig.
Child Forms
You can also apply a form theme to a specific child of your form:
Listing 65-13
This is useful when you want to have a custom theme for a nested form that's different than the one of
your main form. Just specify both your themes:
Listing 65-14
1
2
3
1
2
3
4
5
6
7
8
Now that you've created the customized form template, you need to tell Symfony to use it. Inside the
template where you're actually rendering your form, tell Symfony to use the theme via the setTheme
helper method:
Listing 65-16
1
2
3
the
If you want to apply a theme to a specific child form, pass it to the setTheme method:
Listing 65-17
The :form syntax is based on the functional names for templates: Bundle:Directory. As the
form directory lives in the app/Resources/views directory, the Bundle part is empty, resulting
in :form.
Now, when the blocks from form_div_layout.html.twig8 are imported, the integer_widget block is
called base_integer_widget. This means that when you redefine the integer_widget block, you
can reference the default markup via base_integer_widget:
Listing 65-19
1
2
3
4
5
{% block integer_widget %}
<div class="integer_widget">
{{ block('base_integer_widget') }}
</div>
{% endblock %}
1
2
3
4
5
6
7
8
{# app/Resources/views/Form/fields.html.twig #}
{% extends 'form_div_layout.html.twig' %}
{% block integer_widget %}
<div class="integer_widget">
{{ parent() }}
</div>
{% endblock %}
7. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
8. https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
It is not possible to reference the base block when using PHP as the templating engine. You have to
manually copy the content from the base block to your new template file.
Twig
By
1
2
3
4
5
using
the
inside
the
form/
# app/config/config.yml
twig:
form_themes:
- 'form/fields.html.twig'
# ...
By default, Twig uses a div layout when rendering forms. Some people, however, may prefer to render
forms in a table layout. Use the form_table_layout.html.twig resource to use such a layout:
Listing 65-22
1
2
3
4
5
# app/config/config.yml
twig:
form_themes:
- 'form_table_layout.html.twig'
# ...
If you only want to make the change in one template, add the following line to your template file rather
than adding the template as a resource:
Listing 65-23
Note that the form variable in the above code is the form view variable that you passed to your template.
PHP
By using the following configuration, any customized form fragments inside the app/Resources/
views/Form folder will be used globally when a form is rendered.
Listing 65-24
1
2
3
4
5
6
7
# app/config/config.yml
framework:
templating:
form:
resources:
- 'AppBundle:Form'
# ...
By default, the PHP engine uses a div layout when rendering forms. Some people, however, may prefer to
render forms in a table layout. Use the FrameworkBundle:FormTable resource to use such a layout:
Listing 65-25
1
2
3
# app/config/config.yml
framework:
templating:
4
5
6
form:
resources:
- 'FrameworkBundle:FormTable'
If you only want to make the change in one template, add the following line to your template file rather
than adding the template as a resource:
Listing 65-26
Note that the $form variable in the above code is the form view variable that you passed to your
template.
1
2
3
4
5
6
7
8
9
Here, the _product_name_widget fragment defines the template to use for the field whose id is
product_name (and name is product[name]).
The product portion of the field is the form name, which may be set manually or generated
automatically based on your form type name (e.g. ProductType equates to product). If you're
not sure what your form name is, just view the source of your generated form.
If you want to change the product or name portion of the block name _product_name_widget
you can set the block_name option in your form type:
Listing 65-28
1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Form\FormBuilderInterface;
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->add('name', 'text', array(
'block_name' => 'custom_name',
));
}
You can also override the markup for an entire field row using the same method:
Listing 65-29
1
2
3
4
5
6
7
8
9
10
11
{% block _product_name_row %}
<div class="name_row">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock %}
{{ form_row(form.name) }}
1
2
3
4
5
6
7
8
Not only can you override the rendered widget, but you can also change the complete form row or the
label as well. For the tasks field given above, the block names would be the following:
Part of the Form Block Name
label
_tasks_entry_label
widget
_tasks_entry_widget
row
_tasks_entry_row
There are many different ways to customize how errors are rendered when a form is submitted with
errors. The error messages for a field are rendered when you use the form_errors helper:
Listing 65-31
{{ form_errors(form.age) }}
1
2
3
<ul>
<li>This field is required</li>
</ul>
To override how errors are rendered for all fields, simply copy, paste and customize the form_errors
fragment.
Listing 65-33
1
2
3
4
5
6
7
8
9
10
11
12
{# form_errors.html.twig #}
{% block form_errors %}
{% spaceless %}
{% if errors|length > 0 %}
<ul>
{% for error in errors %}
<li>{{ error.message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endspaceless %}
{% endblock form_errors %}
You can also customize the error output for just one specific field type. To customize only the markup
used for these errors, follow the same directions as above but put the contents in a relative _errors
block (or file in case of PHP templates). For example: text_errors (or text_errors.html.php).
See Form Fragment Naming to find out which specific block or file you have to customize.
Certain errors that are more global to your form (i.e. not specific to just one field) are rendered separately,
usually at the top of your form:
Listing 65-34
{{ form_errors(form) }}
To customize only the markup used for these errors, follow the same directions as above, but now check
if the compound variable is set to true. If it is true, it means that what's being currently rendered is a
collection of fields (e.g. a whole form), and not just an individual field.
Listing 65-35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{# form_errors.html.twig #}
{% block form_errors %}
{% spaceless %}
{% if errors|length > 0 %}
{% if compound %}
<ul>
{% for error in errors %}
<li>{{ error.message }}</li>
{% endfor %}
</ul>
{% else %}
{# ... display the errors for a single field #}
{% endif %}
{% endif %}
{% endspaceless %}
{% endblock form_errors %}
1
2
3
4
5
6
7
8
{# form_row.html.twig #}
{% block form_row %}
<div class="form_row">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
1
2
3
4
5
6
7
8
9
In Twig, if you're making the form customization inside a separate template, use the following:
Listing 65-38
1
2
3
4
5
6
7
8
9
{% extends 'form_div_layout.html.twig' %}
{% block form_label %}
{{ parent() }}
{% if required %}
<span class="required" title="This field is required">*</span>
{% endif %}
{% endblock %}
When using PHP as a templating engine you have to copy the content from the original template:
Listing 65-39
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
label.required:before {
content: "* ";
}
1
2
3
4
5
6
7
8
9
In Twig, if you're making the form customization inside a separate template, use the following:
Listing 65-42
1
2
3
4
5
6
7
8
9
{% extends 'form_div_layout.html.twig' %}
{% block form_widget_simple %}
{{ parent() }}
{% if help is defined %}
<span class="help-block">{{ help }}</span>
{% endif %}
{% endblock %}
When using PHP as a templating engine you have to copy the content from the original template:
Listing 65-43
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
The array passed as the second argument contains form "variables". For more details about this concept
in Twig, see More about Form Variables.
Chapter 66
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Form/TaskType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
// ...
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tags', 'text')
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Task',
));
}
22
23
// ...
}
Internally the tags are stored as an array, but displayed to the user as a simple comma seperated string
to make them easier to edit.
This is a perfect time to attach a custom data transformer to the tags field. The easiest way to do this is
with the CallbackTransformer1 class:
Listing 66-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// src/AppBundle/Form/TaskType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
// ...
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tags', 'text');
$builder->get('tags')
->addModelTransformer(new CallbackTransformer(
function ($tagsAsArray) {
// transform the array to a string
return implode(', ', $tagsAsArray);
},
function ($tagsAsString) {
// transform the string back to an array
return explode(', ', $tagsAsString);
}
))
;
}
// ...
}
The CallbackTransformer takes two callback functions as arguments. The first transforms the
original value into a format that'll be used to render the field. The second does the reverse: it transforms
the submitted value back into the format you'll use in your code.
You can also add the transformer, right when adding the field by changing the format slightly:
Listing 66-3
1
2
3
4
5
$builder->add(
$builder
->create('tags', 'text')
->addModelTransformer(...)
);
1. http://api.symfony.com/2.7/Symfony/Component/Form/CallbackTransformer.html
2. http://api.symfony.com/2.7/Symfony/Component/Form/DataTransformerInterface.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/Form/TaskType.php
namespace AppBundle\Form\Type;
// ...
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', 'textarea')
->add('issue', 'text')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Task'
));
}
// ...
}
Good start! But if you stopped here and submitted the form, the Task's issue property would be a string
(e.g. "55"). How can you transform this into an Issue entity on submit?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Form/DataTransformer/IssueToNumberTransformer.php
namespace AppBundle\Form\DataTransformer;
use
use
use
use
AppBundle\Entity\Issue;
Doctrine\Common\Persistence\ObjectManager;
Symfony\Component\Form\DataTransformerInterface;
Symfony\Component\Form\Exception\TransformationFailedException;
/**
* Transforms an object (issue) to a string (number).
*
* @param Issue|null $issue
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
* @return string
*/
public function transform($issue)
{
if (null === $issue) {
return '';
}
return $issue->getId();
}
/**
* Transforms a string (number) to an object (issue).
*
* @param string $issueNumber
* @return Issue|null
* @throws TransformationFailedException if object (issue) is not found.
*/
public function reverseTransform($issueNumber)
{
// no issue number? It's optional, so that's ok
if (!$issueNumber) {
return;
}
$issue = $this->manager
->getRepository('AppBundle:Issue')
// query for the issue with this id
->find($issueNumber)
;
if (null === $issue) {
// causes a validation error
// this message is not shown to the user
// see the invalid_message option
throw new TransformationFailedException(sprintf(
'An issue with number "%s" does not exist!',
$issueNumber
));
}
return $issue;
}
}
Just like in the first example, a transformer has two directions. The transform() method is responsible
for converting the data used in your code to a format that can be rendered in your form (e.g. an
Issue object to its id, a string). The reverseTransform() method does the reverse: it converts the
submitted value back into the format you want (e.g. convert the id back to the Issue object).
To cause a validation error, throw a TransformationFailedException3. But the message you pass
to this exception won't be shown to the user. You'll set that message with the invalid_message option
(see below).
When null is passed to the transform() method, your transformer should return an equivalent
value of the type it is transforming to (e.g. an empty string, 0 for integers or 0.0 for floats).
3. http://api.symfony.com/2.7/Symfony/Component/Form/Exception/TransformationFailedException.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// src/AppBundle/Form/TaskType.php
namespace AppBundle\Form\Type;
use AppBundle\Form\DataTransformer\IssueToNumberTransformer;
use Doctrine\Common\Persistence\ObjectManager;
// ...
class TaskType extends AbstractType
{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', 'textarea')
->add('issue', 'text', array(
// validation message if the data transformer fails
'invalid_message' => 'That is not a valid issue number',
));
// ...
$builder->get('issue')
->addModelTransformer(new IssueToNumberTransformer($this->manager));
}
// ...
}
Now, when you create your TaskType, you'll need to pass in the entity manager:
Listing 66-7
1
2
3
4
5
To make this step easier (especially if TaskType is embedded into other form type classes), you
might choose to register your form type as a service.
Cool, you're done! Your user will be able to enter an issue number into the text field and it will
be transformed back into an Issue object. This means that, after a successful submission, the Form
component will pass a real Issue object to Task::setIssue() instead of the issue number.
If the issue isn't found, a form error will be created for that field and its error message can be controlled
with the invalid_message field option.
Be careful when adding your transformers. For example, the following is wrong, as the transformer
would be applied to the entire form, instead of just this field:
Listing 66-8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// src/AppBundle/Form/IssueSelectorType.php
namespace AppBundle\Form;
use
use
use
use
use
AppBundle\Form\DataTransformer\IssueToNumberTransformer;
Doctrine\Common\Persistence\ObjectManager;
Symfony\Component\Form\AbstractType;
Symfony\Component\Form\FormBuilderInterface;
Symfony\Component\OptionsResolver\OptionsResolver;
Great! This will act and render like a text field (getParent()), but will automatically have the data
transformer and a nice default value for the invalid_message option.
Next, register your type as a service and tag it with form.type so that it's recognized as a custom field
type:
Listing 66-10
1
2
3
4
5
6
7
# app/config/services.yml
services:
app.type.issue_selector:
class: AppBundle\Form\IssueSelectorType
arguments: ['@doctrine.orm.entity_manager']
tags:
- { name: form.type, alias: issue_selector }
Now, whenever you need to use your special issue_selector field type, it's quite easy:
Listing 66-11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Form/TaskType.php
namespace AppBundle\Form\Type;
use AppBundle\Form\DataTransformer\IssueToNumberTransformer;
// ...
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', 'textarea')
->add('issue', 'issue_selector')
;
}
// ...
}
3. View Data - This is the format that's used to fill in the form fields themselves. It's also the
format in which the user will submit the data. When you call Form::submit($data), the $data is in
the "view" data format.
The two different types of transformers help convert to and from each of these types of data:
Model transformers:
transform:
reverseTransform:
View transformers:
transform:
reverseTransform:
Chapter 67
1
2
3
4
5
6
7
8
9
10
11
// src/AppBundle/Form/Type/ProductType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
Chapter 67: How to Dynamically Modify Forms Using Form Events | 243
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$builder->add('name');
$builder->add('price');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Product'
));
}
public function getName()
{
return 'product';
}
}
If this particular section of code isn't already familiar to you, you probably need to take a step back
and first review the Forms chapter before proceeding.
Assume for a moment that this form utilizes an imaginary "Product" class that has only two properties
("name" and "price"). The form generated from this class will look the exact same regardless if a new
Product is being created or if an existing product is being edited (e.g. a product fetched from the
database).
Suppose now, that you don't want the user to be able to change the name value once the object has been
created. To do this, you can rely on Symfony's EventDispatcher component system to analyze the data on
the object and modify the form based on the Product object's data. In this entry, you'll learn how to add
this level of flexibility to your forms.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AppBundle/Form/Type/ProductType.php
namespace AppBundle\Form\Type;
// ...
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('price');
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
// ... adding the name field if needed
});
}
// ...
}
The goal is to create a name field only if the underlying Product object is new (e.g. hasn't been persisted
to the database). Based on that, the event listener might look like the following:
Listing 67-3
1
2
// ...
public function buildForm(FormBuilderInterface $builder, array $options)
Chapter 67: How to Dynamically Modify Forms Using Form Events | 244
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ...
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$product = $event->getData();
$form = $event->getForm();
//
//
//
if
}
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Form/Type/ProductType.php
namespace AppBundle\Form\Type;
// ...
use AppBundle\Form\EventListener\AddNameFieldSubscriber;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('price');
$builder->addEventSubscriber(new AddNameFieldSubscriber());
}
// ...
}
Now the logic for creating the name field resides in it own subscriber class:
Listing 67-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Form/EventListener/AddNameFieldSubscriber.php
namespace AppBundle\Form\EventListener;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AddNameFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// Tells the dispatcher that you want to listen on the form.pre_set_data
// event and that the preSetData method should be called.
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
1. http://api.symfony.com/2.7/Symfony/Component/Form/FormEvents.html
2. http://api.symfony.com/2.7/Symfony/Component/Form/FormEvents.html
Chapter 67: How to Dynamically Modify Forms Using Form Events | 245
16
17
18
19
20
21
22
23
24
25
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Form/Type/FriendMessageFormType.php
namespace AppBundle\Form\Type;
use
use
use
use
use
Symfony\Component\Form\AbstractType;
Symfony\Component\Form\FormBuilderInterface;
Symfony\Component\Form\FormEvents;
Symfony\Component\Form\FormEvent;
Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
The problem is now to get the current user and create a choice field that contains only this user's friends.
Luckily it is pretty easy to inject a service inside of the form. This can be done in the constructor:
Listing 67-7
1
2
3
4
5
6
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
Chapter 67: How to Dynamically Modify Forms Using Form Events | 246
You might wonder, now that you have access to the User (through the token storage), why not just
use it directly in buildForm and omit the event listener? This is because doing so in the buildForm
method would result in the whole form type being modified and not just this one form instance. This
may not usually be a problem, but technically a single form type could be used on a single request to
create many forms or fields.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// src/AppBundle/FormType/FriendMessageFormType.php
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityRepository;
// ...
class FriendMessageFormType extends AbstractType
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('subject', 'text')
->add('body', 'textarea')
;
Chapter 67: How to Dynamically Modify Forms Using Form Events | 247
56
57
// ...
}
New in version 2.6: The TokenStorageInterface3 was introduced in Symfony 2.6. Prior, you had to
use the getToken() method of SecurityContextInterface4.
The multiple and expanded form options will default to false because the type of the friend field
is entity.
1
2
3
4
5
6
7
8
9
10
11
12
// ...
}
}
1
2
3
4
5
6
7
# app/config/config.yml
services:
app.form.friend_message:
class: AppBundle\Form\Type\FriendMessageFormType
arguments: ['@security.token_storage']
tags:
- { name: form.type, alias: app_friend_message }
If you wish to create it from within a service that has access to the form factory, you then use:
Listing 67-11
$form = $formFactory->create('friend_message');
In a controller that extends the Controller5 class, you can simply call:
Listing 67-12
3. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/Token/Storage/TokenStorageInterface.html
4. http://api.symfony.com/2.7/Symfony/Component/Security/Core/SecurityContextInterface.html
5. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html
Chapter 67: How to Dynamically Modify Forms Using Form Events | 248
1
2
3
4
5
6
7
8
9
10
11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class FriendMessageController extends Controller
{
public function newAction(Request $request)
{
$form = $this->createForm('app_friend_message');
// ...
}
}
You can also easily embed the form type into another form:
Listing 67-13
1
2
3
4
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// src/AppBundle/Form/Type/SportMeetupType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
// ...
class SportMeetupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sport', 'entity', array(
'class'
=> 'AppBundle:Sport',
'placeholder' => '',
))
;
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
Chapter 67: How to Dynamically Modify Forms Using Form Events | 249
34
35
36
37
38
39
40
41
42
// ...
}
New in version 2.6: The placeholder option was introduced in Symfony 2.6 and replaces
empty_value, which is available prior to 2.6.
When you're building this form to display to the user for the first time, then this example works perfectly.
However, things get more difficult when you handle the form submission. This is because the
PRE_SET_DATA event tells us the data that you're starting with (e.g. an empty SportMeetup object),
not the submitted data.
On a form, we can usually listen to the following events:
PRE_SET_DATA
POST_SET_DATA
PRE_SUBMIT
SUBMIT
POST_SUBMIT
New in version 2.3: The events PRE_SUBMIT, SUBMIT and POST_SUBMIT were introduced in Symfony
2.3. Before, they were named PRE_BIND, BIND and POST_BIND.
The key is to add a POST_SUBMIT listener to the field that your new field depends on. If you add a
POST_SUBMIT listener to a form child (e.g. sport), and add new children to the parent form, the Form
component will detect the new field automatically and map it to the submitted client data.
The type would now look like:
Listing 67-15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Form/Type/SportMeetupType.php
namespace AppBundle\Form\Type;
// ...
use Symfony\Component\Form\FormInterface;
use AppBundle\Entity\Sport;
class SportMeetupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sport', 'entity', array(
'class'
=> 'AppBundle:Sport',
'placeholder' => '',
));
;
$formModifier = function (FormInterface $form, Sport $sport = null) {
$positions = null === $sport ? array() : $sport->getAvailablePositions();
$form->add('position', 'entity', array(
'class'
=> 'AppBundle:Position',
'placeholder' => '',
'choices'
=> $positions,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
Chapter 67: How to Dynamically Modify Forms Using Form Events | 250
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $sport);
}
);
}
// ...
}
You can see that you need to listen on these two events and have different callbacks only because in two
different scenarios, the data that you can use is available in different events. Other than that, the listeners
always perform exactly the same things on a given form.
One piece that is still missing is the client-side updating of your form after the sport is selected. This
should be handled by making an AJAX call back to your application. Assume that you have a sport
meetup creation controller:
Listing 67-16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/AppBundle/Controller/MeetupController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\SportMeetup;
use AppBundle\Form\Type\SportMeetupType;
// ...
class MeetupController extends Controller
{
public function createAction(Request $request)
{
$meetup = new SportMeetup();
$form = $this->createForm(new SportMeetupType(), $meetup);
$form->handleRequest($request);
if ($form->isValid()) {
// ... save the meetup, redirect etc.
}
return $this->render(
'AppBundle:Meetup:create.html.twig',
array('form' => $form->createView())
);
}
// ...
}
The associated template uses some JavaScript to update the position form field according to the
current selection in the sport field:
Listing 67-17
1
2
{# app/Resources/views/Meetup/create.html.twig #}
{{ form_start(form) }}
Chapter 67: How to Dynamically Modify Forms Using Form Events | 251
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
{{ form_row(form.sport) }}
{# <select id="meetup_sport" ... #}
{{ form_row(form.position) }} {# <select id="meetup_position" ... #}
{# ... #}
{{ form_end(form) }}
<script>
var $sport = $('#meetup_sport');
// When sport gets selected ...
$sport.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected sport value.
var data = {};
data[$sport.attr('name')] = $sport.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#meetup_position').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#meetup_position')
);
// Position field now displays the appropriate positions.
}
});
});
</script>
The major benefit of submitting the whole form to just extract the updated position field is that no
additional server-side code is needed; all the code from above to generate the submitted form can be
reused.
suppress
form
use
the
The reason for needing to do this is that even if you set validation_groups to false there are still
some integrity checks executed. For example an uploaded file will still be checked to see if it is too large
and the form will still check to see if non-existing fields were submitted. To disable all of this, use a
listener:
Listing 67-18
1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$event->stopPropagation();
}, 900); // Always set a higher priority than ValidationListener
// ...
}
6. http://api.symfony.com/2.7/Symfony/Component/Form/Extension/Validator/EventListener/ValidationListener.html
Chapter 67: How to Dynamically Modify Forms Using Form Events | 252
By doing this, you may accidentally disable something more than just form validation, since the
POST_SUBMIT event may have other listeners.
Chapter 67: How to Dynamically Modify Forms Using Form Events | 253
Chapter 68
First, suppose that each Task belongs to multiple Tag objects. Start by creating a simple Task class:
Listing 68-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Entity/Task.php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
class Task
{
protected $description;
protected $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getTags()
28
29
30
31
{
return $this->tags;
}
}
The ArrayCollection is specific to Doctrine and is basically the same as using an array (but it
must be an ArrayCollection if you're using Doctrine).
Now, create a Tag class. As you saw above, a Task can have many Tag objects:
Listing 68-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Entity/Tag.php
namespace AppBundle\Entity;
class Tag
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
Then, create a form class so that a Tag object can be modified by the user:
Listing 68-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/AppBundle/Form/Type/TagType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class TagType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Tag',
));
}
public function getName()
{
return 'tag';
}
}
With this, you have enough to render a tag form by itself. But since the end goal is to allow the tags of a
Task to be modified right inside the task form itself, create a form for the Task class.
Notice that you embed a collection of TagType forms using the collection field type:
Listing 68-4
1
2
// src/AppBundle/Form/Type/TaskType.php
namespace AppBundle\Form\Type;
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('description');
$builder->add('tags', 'collection', array('type' => new TagType()));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Task',
));
}
public function getName()
{
return 'task';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/AppBundle/Controller/TaskController.php
namespace AppBundle\Controller;
use
use
use
use
use
AppBundle\Entity\Task;
AppBundle\Entity\Tag;
AppBundle\Form\Type\TaskType;
Symfony\Component\HttpFoundation\Request;
Symfony\Bundle\FrameworkBundle\Controller\Controller;
// dummy code - this is here just so that the Task has some tags
// otherwise, this isn't an interesting example
$tag1 = new Tag();
$tag1->setName('tag1');
$task->getTags()->add($tag1);
$tag2 = new Tag();
$tag2->setName('tag2');
$task->getTags()->add($tag2);
// end dummy code
$form = $this->createForm(new TaskType(), $task);
$form->handleRequest($request);
if ($form->isValid()) {
// ... maybe do some form processing, like saving the Task and Tag objects
}
return $this->render('AppBundle:Task:new.html.twig', array(
'form' => $form->createView(),
));
}
}
The corresponding template is now able to render both the description field for the task form as
well as all the TagType forms for any tags that are already related to this Task. In the above controller,
I added some dummy code so that you can see this in action (since a Task has zero tags when first
created).
Listing 68-6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{# src/AppBundle/Resources/views/Task/new.html.twig #}
{# ... #}
{{ form_start(form) }}
{# render the task's only field: description #}
{{ form_row(form.description) }}
<h3>Tags</h3>
<ul class="tags">
{# iterate over each existing tag and render its only field: name #}
{% for tag in form.tags %}
<li>{{ form_row(tag.name) }}</li>
{% endfor %}
</ul>
{{ form_end(form) }}
{# ... #}
When the user submits the form, the submitted data for the tags field are used to construct an
ArrayCollection of Tag objects, which is then set on the tag field of the Task instance.
The tags collection is accessible naturally via $task->getTags() and can be persisted to the database
or used however you need.
So far, this works great, but this doesn't allow you to dynamically add new tags or delete existing tags.
So, while editing existing tags will work great, your user can't actually add any new tags yet.
In this entry, you embed only one collection, but you are not limited to this. You can also embed
nested collection as many levels down as you like. But if you use Xdebug in your development setup,
you may receive a Maximum function nesting level of '100' reached, aborting!
error. This is due to the xdebug.max_nesting_level PHP setting, which defaults to 100.
This directive limits recursion to 100 calls which may not be enough for rendering the form in the
template if you render the whole form at once (e.g form_widget(form)). To fix this you can set
this directive to a higher value (either via a php.ini file or via ini_set1, for example in app/
autoload.php) or render each form field by hand using form_row.
1
2
3
// src/AppBundle/Form/Type/TaskType.php
// ...
1. http://php.net/manual/en/function.ini-set.php
4
5
6
7
8
9
10
11
12
13
14
use Symfony\Component\Form\FormBuilderInterface;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('description');
$builder->add('tags', 'collection', array(
'type'
=> new TagType(),
'allow_add'
=> true,
));
}
In addition to telling the field to accept any number of submitted objects, the allow_add also makes a
"prototype" variable available to you. This "prototype" is a little "template" that contains all the HTML
to be able to render any new "tag" forms. To render it, make the following change to your template:
Listing 68-8
1
2
3
If you render your whole "tags" sub-form at once (e.g. form_row(form.tags)), then the
prototype is automatically available on the outer div as the data-prototype attribute, similar to
what you see above.
The form.tags.vars.prototype is a form element that looks and feels just like the individual
form_widget(tag) elements inside your for loop. This means that you can call form_widget,
form_row or form_label on it. You could even choose to render only one of its fields (e.g. the
name field):
Listing 68-9
{{ form_widget(form.tags.vars.prototype.name)|e }}
On the rendered page, the result will look something like this:
Listing 68-10
The goal of this section will be to use JavaScript to read this attribute and dynamically add new tag forms
when the user clicks a "Add a tag" link. To make things simple, this example uses jQuery and assumes
you have it included somewhere on your page.
Add a script tag somewhere on your page so you can start writing some JavaScript.
First, add a link to the bottom of the "tags" list via JavaScript. Second, bind to the "click" event of that
link so you can add a new tag form (addTagForm will be show next):
Listing 68-11
1
2
3
4
5
6
7
8
9
10
11
var $collectionHolder;
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
The addTagForm function's job will be to use the data-prototype attribute to dynamically add
a new form when this link is clicked. The data-prototype HTML contains the tag text input
element with a name of task[tags][__name__][name] and id of task_tags___name___name.
The __name__ is a little "placeholder", which you'll replace with a unique, incrementing number (e.g.
task[tags][3][name]).
The actual code needed to make this all work can vary quite a bit, but here's one example:
Listing 68-12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
It is better to separate your JavaScript in real JavaScript files than to write it inside the HTML as is
done here.
Now, each time a user clicks the Add a tag link, a new sub form will appear on the page. When the
form is submitted, any new tag forms will be converted into new Tag objects and added to the tags
property of the Task object.
You can find a working example in this JSFiddle2.
If you want to customize the HTML code in the prototype, read How to Customize a Collection Prototype.
To make handling these new tags easier, add an "adder" and a "remover" method for the tags in the Task
class:
Listing 68-13
1
2
// src/AppBundle/Entity/Task.php
namespace AppBundle\Entity;
2. http://jsfiddle.net/847Kf/4/
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// ...
class Task
{
// ...
public function addTag(Tag $tag)
{
$this->tags->add($tag);
}
public function removeTag(Tag $tag)
{
// ...
}
}
Next, add a by_reference option to the tags field and set it to false:
Listing 68-14
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Form/Type/TaskType.php
// ...
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->add('tags', 'collection', array(
// ...
'by_reference' => false,
));
}
With these two changes, when the form is submitted, each new Tag object is added to the Task class
by calling the addTag method. Before this change, they were added internally by the form by calling
$task->getTags()->add($tag). That was just fine, but forcing the use of the "adder" method
makes handling these new Tag objects easier (especially if you're using Doctrine, which you will learn
about next!).
You have to create both addTag and removeTag methods, otherwise the form will still use
setTag even if by_reference is false. You'll learn more about the removeTag method later in
this article.
AppBundle\Entity\Task#tags
To fix this, you may choose to "cascade" the persist operation automatically from the Task object to
any related tags. To do this, add the cascade option to your ManyToMany metadata:
Listing 68-15
1
2
3
4
5
6
7
8
// src/AppBundle/Entity/Task.php
// ...
/**
* @ORM\ManyToMany(targetEntity="Tag", cascade={"persist"})
*/
protected $tags;
A second potential issue deals with the Owning Side and Inverse Side3 of Doctrine relationships. In
this example, if the "owning" side of the relationship is "Task", then persistence will work fine as the
tags are properly added to the Task. However, if the owning side is on "Tag", then you'll need to do
a little bit more work to ensure that the correct side of the relationship is modified.
The trick is to make sure that the single "Task" is set on each "Tag". One easy way to do this is to
add some extra logic to addTag(), which is called by the form type since by_reference is set to
false:
Listing 68-16
1
2
3
4
5
6
7
8
9
// src/AppBundle/Entity/Task.php
// ...
public function addTag(Tag $tag)
{
$tag->addTask($this);
$this->tags->add($tag);
}
1
2
3
4
5
6
7
8
9
// src/AppBundle/Entity/Tag.php
// ...
public function addTask(Task $task)
{
if (!$this->tasks->contains($task)) {
$this->tasks->add($task);
}
}
If you have a one-to-many relationship, then the workaround is similar, except that you can simply
call setTask from inside addTag.
3. http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Form/Type/TaskType.php
// ...
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
$builder->add('tags', 'collection', array(
// ...
'allow_delete' => true,
));
}
Now, you need to put some code into the removeTag method of Task:
Listing 68-19
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Entity/Task.php
// ...
class Task
{
// ...
public function removeTag(Tag $tag)
{
$this->tags->removeElement($tag);
}
}
Template Modifications
The allow_delete option has one consequence: if an item of a collection isn't sent on submission, the
related data is removed from the collection on the server. The solution is thus to remove the form element
from the DOM.
First, add a "delete this tag" link to each tag form:
Listing 68-20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('ul.tags');
1
2
3
4
5
6
7
8
9
10
11
12
function addTagFormDeleteLink($tagFormLi) {
var $removeFormA = $('<a href="#">delete this tag</a>');
$tagFormLi.append($removeFormA);
$removeFormA.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
When a tag form is removed from the DOM and submitted, the removed Tag object will not be included
in the collection passed to setTags. Depending on your persistence layer, this may or may not be
enough to actually remove the relationship between the removed Tag and Task object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// src/AppBundle/Controller/TaskController.php
use Doctrine\Common\Collections\ArrayCollection;
// ...
public function editAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$task = $em->getRepository('AppBundle:Task')->find($id);
if (!$task) {
throw $this->createNotFoundException('No task found for id '.$id);
}
$originalTags = new ArrayCollection();
// if you wanted to delete the Tag entirely, you can also do that
// $em->remove($tag);
}
}
$em->persist($task);
$em->flush();
As you can see, adding and removing the elements correctly can be tricky. Unless you have a manyto-many relationship where Task is the "owning" side, you'll need to do extra work to make sure that
the relationship is properly updated (whether you're adding new tags or removing existing tags) on
each Tag object itself.
Chapter 69
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/AppBundle/Form/Type/GenderType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class GenderType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'choices' => array(
'm' => 'Male',
'f' => 'Female',
)
));
}
public function getParent()
{
return 'choice';
}
1. http://api.symfony.com/2.7/Symfony/Component/Form/AbstractType.html
23
24
25
26
27
28
The location of this file is not important - the Form\Type directory is just a convention.
Here, the return value of the getParent function indicates that you're extending the choice field type.
This means that, by default, you inherit all of the logic and rendering of that field type. To see some of
the logic, check out the ChoiceType2 class. There are three methods that are particularly important:
buildForm()
Each field type has a buildForm method, which is where you configure and build any field(s). Notice
that this is the same method you use to setup your forms, and it works the same here.
buildView()
This method is used to set any extra variables you'll need when rendering your field in a template.
For example, in ChoiceType3, a multiple variable is set and used in the template to set (or not set) the
multiple attribute on the select field. See Creating a Template for the Field for more details.
New in version 2.7: The configureOptions() method was introduced in Symfony 2.7. Previously, the
method was called setDefaultOptions().
configureOptions()
This defines options for your form type that can be used in buildForm() and buildView(). There are a lot
of options common to all fields (see form Field Type), but you can create any others that you need
here.
If you're creating a field that consists of many fields, then be sure to set your "parent" type as form
or something that extends form. Also, if you need to modify the "view" of any of your child types
from your parent type, use the finishView() method.
The getName() method returns an identifier which should be unique in your application. This is used
in various places, such as when customizing how your form type will be rendered.
The goal of this field was to extend the choice type to enable selection of a gender. This is achieved by
fixing the choices to a list of possible genders.
Listing 69-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{# app/Resources/views/form/fields.html.twig #}
{% block gender_widget %}
{% spaceless %}
{% if expanded %}
<ul {{ block('widget_container_attributes') }}>
{% for child in form %}
<li>
{{ form_widget(child) }}
{{ form_label(child) }}
</li>
{% endfor %}
</ul>
{% else %}
{# just let the choice widget render the select tag #}
{{ block('choice_widget') }}
{% endif %}
{% endspaceless %}
{% endblock %}
Make sure the correct widget prefix is used. In this example the name should be gender_widget,
according to the value returned by getName. Further, the main config file should point to the
custom form template so that it's used when rendering all forms.
When using Twig this is:
Listing 69-3
1
2
3
4
# app/config/config.yml
twig:
form_themes:
- 'form/fields.html.twig'
For the PHP templating engine, your configuration should look like this:
Listing 69-4
1
2
3
4
5
6
# app/config/config.yml
framework:
templating:
form:
resources:
- ':form:fields.html.php'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Form/Type/AuthorType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class AuthorType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('gender_code', new GenderType(), array(
'placeholder' => 'Choose a gender',
));
}
}
But this only works because the GenderType() is very simple. What if the gender codes were stored
in configuration or in a database? The next section explains how more complex field types solve this
problem.
New in version 2.6: The placeholder option was introduced in Symfony 2.6 and replaces
empty_value, which is available prior to 2.6.
1
2
3
4
5
# app/config/config.yml
parameters:
genders:
m: Male
f: Female
To use the parameter, define your custom field type as a service, injecting the genders parameter value
as the first argument to its to-be-created __construct function:
Listing 69-7
1
2
3
4
5
6
7
8
# src/AppBundle/Resources/config/services.yml
services:
app.form.type.gender:
class: AppBundle\Form\Type\GenderType
arguments:
- '%genders%'
tags:
- { name: form.type, alias: app_gender }
Make sure the services file is being imported. See Importing Configuration with imports for details.
Be sure that the alias attribute of the tag corresponds with the value returned by the getName method
defined earlier. You'll see the importance of this in a moment when you use the custom field type. But
first, add a __construct method to GenderType, which receives the gender configuration:
Listing 69-8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Form/Type/GenderType.php
namespace AppBundle\Form\Type;
use Symfony\Component\OptionsResolver\OptionsResolver;
// ...
// ...
class GenderType extends AbstractType
{
private $genderChoices;
public function __construct(array $genderChoices)
{
$this->genderChoices = $genderChoices;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'choices' => $this->genderChoices,
22
23
24
25
26
));
}
// ...
}
Great! The GenderType is now fueled by the configuration parameters and registered as a service.
Additionally, because you used the form.type alias in its configuration, using the field is now much
easier:
Listing 69-9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/AppBundle/Form/Type/AuthorType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
// ...
class AuthorType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('gender_code', 'gender', array(
'placeholder' => 'Choose a gender',
));
}
}
Notice that instead of instantiating a new instance, you can just refer to it by the alias used in your service
configuration, gender. Have fun!
Chapter 70
When creating a form type extension, you can either implement the FormTypeExtensionInterface1
interface or extend the AbstractTypeExtension2 class. In most cases, it's easier to extend the abstract
class:
Listing 70-1
// src/AppBundle/Form/Extension/ImageTypeExtension.php
namespace AppBundle\Form\Extension;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use Symfony\Component\Form\AbstractTypeExtension;
class ImageTypeExtension extends AbstractTypeExtension
{
/**
* Returns the name of the type being extended.
*
* @return string The name of the type being extended
*/
public function getExtendedType()
{
return 'file';
}
}
The only method you must implement is the getExtendedType function. It is used to indicate the
name of the form type that will be extended by your extension.
The value you return in the getExtendedType method corresponds to the value returned by the
getName method in the form type class you wish to extend.
In addition to the getExtendedType function, you will probably want to override one of the following
methods:
buildForm()
buildView()
configureOptions()
finishView()
For more information on what those methods do, you can refer to the Creating Custom Field Types
cookbook article.
1
2
3
4
5
services:
app.image_type_extension:
class: AppBundle\Form\Extension\ImageTypeExtension
tags:
- { name: form.type_extension, alias: file }
The alias key of the tag is the type of field that this extension should be applied to. In your case, as you
want to extend the file field type, you will use file as an alias.
1. http://api.symfony.com/2.7/Symfony/Component/Form/FormTypeExtensionInterface.html
2. http://api.symfony.com/2.7/Symfony/Component/Form/AbstractTypeExtension.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/AppBundle/Entity/Media.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Media
{
// ...
/**
* @var string The path - typically stored in the database
*/
private $path;
// ...
/**
* Get the image URL
*
* @return null|string
*/
public function getWebPath()
{
// ... $webPath being the full image URL, to be used in templates
return $webPath;
}
}
Your form type extension class will need to do two things in order to extend the file form type:
1. Override the configureOptions method in order to add an image_path option;
2. Override the buildView methods in order to pass the image URL to the view.
The logic is the following: when adding a form field of type file, you will be able to specify a new
option: image_path. This option will tell the file field how to get the actual image URL in order to
display it in the view:
Listing 70-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/Form/Extension/ImageTypeExtension.php
namespace AppBundle\Form\Extension;
use
use
use
use
use
Symfony\Component\Form\AbstractTypeExtension;
Symfony\Component\Form\FormView;
Symfony\Component\Form\FormInterface;
Symfony\Component\PropertyAccess\PropertyAccess;
Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Add the image_path option
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
*
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefined(array('image_path'));
}
/**
* Pass the image URL to the view
*
* @param FormView $view
* @param FormInterface $form
* @param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
if (isset($options['image_path'])) {
$parentData = $form->getParent()->getData();
$imageUrl = null;
if (null !== $parentData) {
$accessor = PropertyAccess::createPropertyAccessor();
$imageUrl = $accessor->getValue($parentData, $options['image_path']);
}
// set an "image_url" variable that will be available when rendering this field
$view->vars['image_url'] = $imageUrl;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
{# src/AppBundle/Resources/views/Form/fields.html.twig #}
{% extends 'form_div_layout.html.twig' %}
{% block file_widget %}
{% spaceless %}
{{ block('form_widget') }}
{% if image_url is not null %}
<img src="{{ asset(image_url) }}"/>
{% endif %}
{% endspaceless %}
{% endblock %}
You will need to change your config file or explicitly specify how you want your form to be themed in
order for Symfony to use your overridden block. See What are Form Themes? for more information.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AppBundle/Form/Type/MediaType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class MediaType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text')
->add('file', 'file', array('image_path' => 'webPath'));
}
public function getName()
{
return 'app_media';
}
}
When displaying the form, if the underlying model has already been associated with an image, you will
see it displayed next to the file input.
Chapter 71
Listing 71-2
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/AppBundle/Entity/Company.php
namespace AppBundle\Entity;
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/AppBundle/Entity/Customer.php
namespace AppBundle\Entity;
class Company
{
private $name;
private $website;
private
private
private
private
$address;
$zipcode;
$city;
$country;
class Customer
{
private $firstName;
private $lastName;
private
private
private
private
$address;
$zipcode;
$city;
$country;
As you can see, each entity shares a few of the same fields: address, zipcode, city, country.
Start with building two forms for these entities, CompanyType and CustomerType:
PDF brought to you by
generated on July 28, 2016
Listing 71-3
Listing 71-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Form/Type/CompanyType.php
namespace AppBundle\Form\Type;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Form/Type/CustomerType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class CompanyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text')
->add('website', 'text');
}
}
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
class CustomerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', 'text')
->add('lastName', 'text');
}
}
Instead of including the duplicated fields address, zipcode, city and country in both of these
forms, create a third form called LocationType for that:
Listing 71-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Form/Type/LocationType.php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class LocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('address', 'textarea')
->add('zipcode', 'text')
->add('city', 'text')
->add('country', 'text');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'inherit_data' => true
));
}
public function getName()
{
return 'location';
}
}
The location form has an interesting option set, namely inherit_data. This option lets the form
inherit its data from its parent form. If embedded in the company form, the fields of the location form
PDF brought to you by
generated on July 28, 2016
will access the properties of the Company instance. If embedded in the customer form, the fields will
access the properties of the Customer instance instead. Easy, eh?
Instead of setting the inherit_data option inside LocationType, you can also (just like with
any option) pass it in the third argument of $builder->add().
Finally, make this work by adding the location form to your two original forms:
Listing 71-6
Listing 71-7
1
2
3
4
5
6
7
8
9
// src/AppBundle/Form/Type/CompanyType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
1
2
3
4
5
6
7
8
9
// src/AppBundle/Form/Type/CustomerType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...
That's it! You have extracted duplicated field definitions to a separate location form that you can reuse
wherever you need it.
Forms with the inherit_data option set cannot have *_SET_DATA event listeners.
Chapter 72
FormTypeInterface1),
The only class that is usually manipulated by programmers is the form type class which serves as a form
blueprint. It is used to generate the Form and the FormView. You could test it directly by mocking its
interactions with the factory but it would be complex. It is better to pass it to FormFactory like it is done
in a real application. It is simple to bootstrap and you can trust the Symfony components enough to use
them as a testing base.
There is already a class that you can benefit from for simple FormTypes testing: TypeTestCase4. It is
used to test the core types and you can use it to test your types too.
New in version 2.3: The TypeTestCase has moved to the Symfony\Component\Form\Test
namespace
in
2.3.
Previously,
the
class
was
located
in
Symfony\Component\Form\Tests\Extension\Core\Type.
Depending on the way you installed your Symfony or Symfony Form component the tests may not
be downloaded. Use the --prefer-source option with Composer if this is the case.
The Basics
The simplest TypeTestCase implementation looks like the following:
Listing 72-1
1
2
3
4
5
// src/AppBundle/Tests/Form/Type/TestedTypeTest.php
namespace AppBundle\Tests\Form\Type;
use AppBundle\Form\Type\TestedType;
use AppBundle\Model\TestObject;
1. http://api.symfony.com/2.7/Symfony/Component/Form/FormTypeInterface.html
2. http://api.symfony.com/2.7/Symfony/Component/Form/Form.html
3. http://api.symfony.com/2.7/Symfony/Component/Form/FormView.html
4. http://api.symfony.com/2.7/Symfony/Component/Form/Test/TypeTestCase.html
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use Symfony\Component\Form\Test\TypeTestCase;
class TestedTypeTest extends TypeTestCase
{
public function testSubmitValidData()
{
$formData = array(
'test' => 'test',
'test2' => 'test2',
);
$type = new TestedType();
$form = $this->factory->create($type);
$object = TestObject::fromArray($formData);
This test checks that none of your data transformers used by the form failed. The isSynchronized()5
method is only set to false if a data transformer throws an exception:
Listing 72-3
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
Don't test the validation: it is applied by a listener that is not active in the test case and it relies on
validation configuration. Instead, unit test your custom constraints directly.
Next, verify the submission and mapping of the form. The test below checks if all the fields are correctly
specified:
Listing 72-4
$this->assertEquals($object, $form->getData());
Finally, check the creation of the FormView. You should check if all widgets you want to display are
available in the children property:
Listing 72-5
1
2
3
4
5
6
$view = $form->createView();
$children = $view->children;
foreach (array_keys($formData) as $key) {
$this->assertArrayHasKey($key, $children);
}
5. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_isSynchronized
// src/AppBundle/Form/Type/TestedType.php
// ... the buildForm method
$builder->add('app_test_child_type');
To create your form correctly, you need to make the type available to the form factory in your test. The
easiest way is to register it manually before creating the parent form using the PreloadedExtension
class:
Listing 72-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Tests/Form/Type/TestedTypeTests.php
namespace AppBundle\Tests\Form\Type;
use
use
use
use
AppBundle\Form\Type\TestedType;
AppBundle\Model\TestObject;
Symfony\Component\Form\Test\TypeTestCase;
Symfony\Component\Form\PreloadedExtension;
Make sure the child type you add is well tested. Otherwise you may be getting errors that are not
related to the form you are currently testing but to its children.
1
2
3
4
// src/AppBundle/Tests/Form/Type/TestedTypeTests.php
namespace AppBundle\Tests\Form\Type;
use AppBundle\Form\Type\TestedType;
6. http://api.symfony.com/2.7/Symfony/Component/OptionsResolver/Exception/InvalidOptionsException.html
7. http://api.symfony.com/2.7/Symfony/Component/Form/Test/TypeTestCase.html#method_getExtensions
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use
use
use
use
use
use
AppBundle\Model\TestObject;
Symfony\Component\Form\Extension\Validator\ValidatorExtension;
Symfony\Component\Form\Forms;
Symfony\Component\Form\FormBuilder;
Symfony\Component\Form\Test\TypeTestCase;
Symfony\Component\Validator\ConstraintViolationList;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/AppBundle/Tests/Form/Type/TestedTypeTests.php
namespace AppBundle\Tests\Form\Type;
use AppBundle\Form\Type\TestedType;
use AppBundle\Model\TestObject;
use Symfony\Component\Form\Test\TypeTestCase;
class TestedTypeTest extends TypeTestCase
{
/**
* @dataProvider getValidTestData
*/
public function testForm($data)
{
// ... your test
}
public function getValidTestData()
{
return array(
array(
'data' => array(
'test' => 'test',
'test2' => 'test2',
),
),
array(
'data' => array(),
),
array(
'data' => array(
'test' => null,
'test2' => null,
),
),
);
8. https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers
38
39
}
}
The code above will run your test three times with 3 different sets of data. This allows for decoupling the
test fixtures from the tests and easily testing against multiple sets of data.
You can also pass another argument, such as a boolean if the form has to be synchronized with the given
set of data or not etc.
Chapter 73
1
2
3
4
5
6
7
8
9
10
11
12
By default, empty_data is set to null. Or, if you have specified a data_class option for your form
class, it will default to a new instance of that class. That instance will be created by calling the constructor
with no arguments.
If you want to override this default behavior, there are two ways to do this.
1
2
3
4
5
6
7
8
9
// src/AppBundle/Form/Type/BlogType.php
// ...
use Symfony\Component\Form\AbstractType;
use AppBundle\Entity\Blog;
use Symfony\Component\OptionsResolver\OptionsResolver;
class BlogType extends AbstractType
{
Chapter 73: How to Configure empty Data for a Form Class | 284
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private $someDependency;
public function __construct($someDependency)
{
$this->someDependency = $someDependency;
}
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'empty_data' => new Blog($this->someDependency),
));
}
}
You can instantiate your class however you want. In this example, we pass some dependency into the
BlogType when we instantiate it, then use that to instantiate the Blog class. The point is, you can set
empty_data to the exact "new" object that you want to use.
1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormInterface;
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'empty_data' => function (FormInterface $form) {
return new Blog($form->get('title')->getData());
},
));
}
Chapter 73: How to Configure empty Data for a Form Class | 285
Chapter 74
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
return $this->render('AppBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
1. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_handleRequest
Chapter 74: How to Use the submit() Function to Handle Form Submissions | 286
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Symfony\Component\HttpFoundation\Request;
// ...
public function newAction(Request $request)
{
$form = $this->createFormBuilder()
// ...
->getForm();
if ($request->isMethod('POST')) {
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
// perform some action...
return $this->redirectToRoute('task_success');
}
}
return $this->render('AppBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
$form->get('firstName')->submit('Fabien');
When submitting a form via a "PATCH" request, you may want to update only a few submitted
fields. To achieve this, you may pass an optional second boolean parameter to submit(). Passing
false will remove any missing fields within the form object. Otherwise, the mising fields will be set
to null.
1
2
use Symfony\Component\HttpFoundation\Request;
// ...
2. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_handleRequest
3. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_submit
4. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_submit
5. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_submit
6. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_submit
7. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html
Chapter 74: How to Use the submit() Function to Handle Form Submissions | 287
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Passing the Request8 directly to submit()9 still works, but is deprecated and will be removed in
Symfony 3.0. You should use the method handleRequest()10 instead.
8. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html
9. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_submit
10. http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_handleRequest
Chapter 74: How to Use the submit() Function to Handle Form Submissions | 288
Chapter 75
Chapter 75: How to Use the virtual Form Field Option | 289
Chapter 76
Installing Bower
Bower1 is built on top of Node.js2. Make sure you have that installed and then run:
Listing 76-1
After this command has finished, run bower in your terminal to find out if it's installed correctly.
If you don't want to have NodeJS on your computer, you can also use BowerPHP3 (an unofficial PHP
port of Bower). Beware that this is currently in beta status. If you're using BowerPHP, use bowerphp
instead of bower in the examples.
1
2
3
{
"directory": "web/assets/vendor/"
}
1. http://bower.io
2. https://nodejs.org
3. http://bowerphp.org/
If you're using a front-end build system like Gulp4 or Grunt5, then you can set the directory to
whatever you want. Typically, you'll use these tools to ultimately move all assets into the web/
directory.
This will install Bootstrap and its dependencies in web/assets/vendor/ (or whatever directory you
configured in .bowerrc).
For more details on how to use Bower, check out Bower documentation7.
1
2
3
4
5
6
7
8
9
10
11
12
{# app/Resources/views/layout.html.twig #}
<!doctype html>
<html>
<head>
{# ... #}
<link rel="stylesheet"
href="{{ asset('assets/vendor/bootstrap/dist/css/bootstrap.min.css') }}">
</head>
{# ... #}
</html>
Great job! Your site is now using Bootstrap. You can now easily upgrade bootstrap to the latest version
and manage other front-end dependencies too.
4. http://gulpjs.com/
5. http://gruntjs.com/
6. http://getbootstrap.com/
7. http://bower.io/
Why? Unlike Composer, Bower currently does not have a "lock" feature, which means that there's no
guarantee that running bower install on a different server will give you the exact assets that you have
on other machines. For more details, read the article Checking in front-end dependencies8.
But, it's very possible that Bower will add a lock feature in the future (e.g. bower/bower#17489).
If you don't care too much about having exact the same versions, you can only commit the bower.json
file. Running bower install will give you the latest versions within the specified version range of each
package in bower.json. Using strict version constraints (e.g. 1.10.*) is often enough to ensure only
bringing in compatible versions.
8. http://addyosmani.com/blog/checking-in-front-end-dependencies/
9. https://github.com/bower/bower/pull/1748
Chapter 77
Once the command finishes its execution, you'll have a new Symfony project created in the
my_project/ directory and based on the most recent code found in the 2.7 branch.
If you want to test a beta version, use beta as the value of the stability option:
Listing 77-2
1
2
{
"require": {
Chapter 77: How to Install or Upgrade to the Latest, Unreleased Symfony Version | 293
3
4
5
"symfony/symfony" : "2.7.*@dev"
}
}
Finally, open a command console, enter your project directory and execute the following command to
update your project dependencies:
Listing 77-4
If you prefer to test a Symfony beta version, replace the "2.7.*@dev" constraint by "2.7.0-beta1"
to install a specific beta number or 2.7.*@beta to get the most recent beta version.
After upgrading the Symfony version, read the Symfony Upgrading Guide to learn how you should
proceed to update your application's code in case the new Symfony version has deprecated some of its
features.
If you use Git to manage the project's code, it's a good practice to create a new branch to test the
new Symfony version. This solution avoids introducing any issue in your application and allows you
to test the new version with total confidence:
Listing 77-5
1
2
3
4
5
6
7
8
$
$
#
$
cd projects/my_project/
git checkout -b testing_new_symfony
... update composer.json configuration
composer update symfony/symfony
Chapter 77: How to Install or Upgrade to the Latest, Unreleased Symfony Version | 294
Chapter 78
Usage
To log a message simply get the logger service from the container in your controller:
Listing 78-1
1
2
3
4
5
6
7
8
// ...
}
The logger service has different methods for different logging levels. See LoggerInterface2 for details on
which methods are available.
The basic handler is the StreamHandler which writes logs in a stream (by default in the app/logs/
prod.log in the prod environment and app/logs/dev.log in the dev environment).
1. https://github.com/Seldaek/monolog
2. https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php
Monolog comes also with a powerful built-in handler for the logging in prod environment:
FingersCrossedHandler. It allows you to store the messages in a buffer and to log them only if a
message reaches the action level (error in the configuration provided in the Symfony Standard Edition)
by forwarding the messages to another handler.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# app/config/config.yml
monolog:
handlers:
applog:
type: stream
path: /var/log/symfony.log
level: error
main:
type: fingers_crossed
action_level: warning
handler: file
file:
type: stream
level: debug
syslog:
type: syslog
level: error
The above configuration defines a stack of handlers which will be called in the order they are defined.
The handler named "file" will not be included in the stack itself as it is used as a nested handler of
the fingers_crossed handler.
If you want to change the config of MonologBundle in another config file you need to redefine the
whole stack. It cannot be merged because the order matters and a merge does not allow to control
the order.
1
2
3
4
5
6
7
8
9
10
# app/config/config.yml
services:
my_formatter:
class: Monolog\Formatter\JsonFormatter
monolog:
handlers:
file:
type: stream
level: debug
formatter: my_formatter
1
2
3
4
5
6
7
8
9
10
# app/config/config_dev.yml
monolog:
handlers:
main:
type: rotating_file
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
# max number of log files to keep
# defaults to zero, which means infinite files
max_files: 10
1
2
3
4
5
6
7
8
# app/config/config.yml
monolog:
use_microseconds: false
handlers:
applog:
type: stream
path: /var/log/symfony.log
level: error
3. https://fedorahosted.org/logrotate/
Listing 78-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace AppBundle;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# app/config/config.yml
services:
monolog.formatter.session_request:
class: Monolog\Formatter\LineFormatter
arguments:
- "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%%
%%extra%%\n"
use Symfony\Component\HttpFoundation\Session\Session;
class SessionRequestProcessor
{
private $session;
private $token;
public function __construct(Session $session)
{
$this->session = $session;
}
public function processRecord(array $record)
{
if (null === $this->token) {
try {
$this->token = substr($this->session->getId(), 0, 8);
} catch (\RuntimeException $e) {
$this->token = '????????';
}
$this->token .= '-' . substr(uniqid(), -8);
}
$record['extra']['token'] = $this->token;
return $record;
}
}
monolog.processor.session_request:
class: AppBundle\SessionRequestProcessor
arguments: ['@session']
tags:
- { name: monolog.processor, method: processRecord }
monolog:
handlers:
main:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
formatter: monolog.formatter.session_request
If you use several handlers, you can also register a processor at the handler level or at the channel
level instead of registering it globally (see the following sections).
1
2
3
# app/config/config.yml
services:
monolog.processor.session_request:
4
5
6
7
class: AppBundle\SessionRequestProcessor
arguments: ['@session']
tags:
- { name: monolog.processor, method: processRecord, handler: main }
1
2
3
4
5
6
7
# app/config/config.yml
services:
monolog.processor.session_request:
class: AppBundle\SessionRequestProcessor
arguments: ['@session']
tags:
- { name: monolog.processor, method: processRecord, channel: main }
Chapter 79
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# app/config/config_prod.yml
monolog:
handlers:
mail:
type:
fingers_crossed
# 500 errors are logged at the critical level
action_level: critical
# to also log 400 level errors (but not 404's):
# action_level: error
# excluded_404s:
#
- ^/
handler:
deduplicated
deduplicated:
type:
deduplication
handler: swift
swift:
type:
swift_mailer
from_email: '[email protected]'
to_email:
'[email protected]'
# or list of recipients
# to_email: ['[email protected]', '[email protected]', ...]
subject:
'An Error Occurred! %%message%%'
level:
debug
formatter: monolog.formatter.html
content_type: text/html
The mail handler is a fingers_crossed handler which means that it is only triggered when the action
level, in this case critical is reached. The critical level is only triggered for 5xx HTTP code errors.
If this level is reached once, the fingers_crossed handler will log all messages regardless of their level.
The handler setting means that the output is then passed onto the deduplicated handler.
1. https://github.com/Seldaek/monolog
If you want both 400 level and 500 level errors to trigger an email, set the action_level to error
instead of critical. See the code above for an example.
The deduplicated handler simply keeps all the messages for a request and then passes them onto the
nested handler in one go, but only if the records are unique over a given period of time (60 seconds by
default). If the records are duplicates they are simply discarded. Adding this handler reduces the amount
of notifications to a manageable level, specially in critical failure scenarios.
The messages are then passed to the swift handler. This is the handler that actually deals with emailing
you the error. The settings for this are straightforward, the to and from addresses, the formatter, the
content type and the subject.
You can combine these handlers with other handlers so that the errors still get logged on the server as
well as the emails being sent:
Listing 79-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# app/config/config_prod.yml
monolog:
handlers:
main:
type:
fingers_crossed
action_level: critical
handler:
grouped
grouped:
type:
group
members: [streamed, deduplicated]
streamed:
type: stream
path: '%kernel.logs_dir%/%kernel.environment%.log'
level: debug
deduplicated:
type:
deduplication
handler: swift
swift:
type:
swift_mailer
from_email: '[email protected]'
to_email:
'[email protected]'
subject:
'An Error Occurred! %%message%%'
level:
debug
formatter: monolog.formatter.html
content_type: text/html
This uses the group handler to send the messages to the two group members, the deduplicated and
the stream handlers. The messages will now be both written to the log file and emailed.
Chapter 80
When a lot of logging has to happen, it's cumbersome to print information depending on the verbosity
settings (-v, -vv, -vvv) because the calls need to be wrapped in conditions. The code quickly gets
verbose or dirty. For example:
Listing 80-1
1
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) {
$output->writeln('Some info');
}
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln('Some more info');
}
}
Instead of using these semantic methods to test for each of the verbosity levels, the MonologBridge2
provides a ConsoleHandler3 that listens to console events and writes log messages to the console output
depending on the current log level and the console verbosity.
The example above could then be rewritten as:
Listing 80-2
1
2
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
1. http://api.symfony.com/2.7/Symfony/Component/Console/Output/OutputInterface.html
2. https://github.com/symfony/MonologBridge
3. https://github.com/symfony/MonologBridge/blob/master/Handler/ConsoleHandler.php
3
4
5
6
7
8
9
10
11
Depending on the verbosity level that the command is run in and the user's configuration (see below),
these messages may or may not be displayed to the console. If they are displayed, they are timestamped
and colored appropriately. Additionally, error logs are written to the error output (php://stderr). There
is no need to conditionally handle the verbosity settings anymore.
The Monolog console handler is enabled in the Monolog configuration. This is the default in Symfony
Standard Edition 2.4 too.
Listing 80-3
1
2
3
4
5
# app/config/config.yml
monolog:
handlers:
console:
type: console
With the verbosity_levels option you can adapt the mapping between verbosity and log level.
In the given example it will also show notices in normal verbosity mode (instead of warnings only).
Additionally, it will only use messages logged with the custom my_channel channel and it changes the
display style via a custom formatter (see the MonologBundle reference for more information):
Listing 80-4
1
2
3
4
5
6
7
8
9
# app/config/config.yml
monolog:
handlers:
console:
type:
console
verbosity_levels:
VERBOSITY_NORMAL: NOTICE
channels: my_channel
formatter: my_formatter
Listing 80-5
1
2
3
4
5
6
# app/config/services.yml
services:
my_formatter:
class: Symfony\Bridge\Monolog\Formatter\ConsoleFormatter
arguments:
- "[%%datetime%%] %%start_tag%%%%message%%%%end_tag%% (%%level_name%%) %%context%% %%extra%%\n"
Chapter 81
1
2
3
4
5
6
7
8
9
# app/config/config.yml
monolog:
handlers:
main:
# ...
type: fingers_crossed
handler: ...
excluded_404s:
- ^/phpmyadmin
Chapter 81: How to Configure Monolog to Exclude 404 Errors from the Log | 304
Chapter 82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# app/config/config.yml
monolog:
handlers:
security:
# log all messages (since debug is the lowest level)
level:
debug
type:
stream
path:
'%kernel.logs_dir%/security.log'
channels: [security]
# an example of *not* logging security channel messages for this handler
main:
# ...
# channels: ['!security']
The channels configuration only works for top level handlers. Handlers that are nested inside a
group, buffer, filter, fingers crossed or other such handler will ignore this configuration and will
process every message passed to them.
YAML Specification
You can specify the configuration by many forms:
Listing 82-2
1
2
3
4
5
6
7
channels: ~
1
2
3
# app/config/config.yml
monolog:
channels: ['foo', 'bar']
With this, you can now send log messages to the foo channel by using the automatically registered logger
service monolog.logger.foo.
Chapter 83
1
2
3
4
5
interface DataCollectorInterface
{
function collect(Request $request, Response $response, \Exception $exception = null);
function getName();
}
The getName()2 method returns the name of the data collector and must be unique in the application.
This value is also used to access the information later on (see How to Use the Profiler in a Functional Test
for instance).
The collect()3 method is responsible for storing the collected data in local properties.
Most of the time, it is convenient to extend DataCollector4 and populate the $this->data property
(it takes care of serializing the $this->data property). Imagine you create a new data collector that
collects the method and accepted content types from the request:
Listing 83-2
1
2
3
4
5
6
7
8
// src/AppBundle/DataCollector/RequestCollector.php
namespace AppBundle\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
class RequestCollector extends DataCollector
{
public function collect(Request $request, Response $response, \Exception $exception = null)
1. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/DataCollector/DataCollectorInterface.html
2. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/DataCollector/DataCollectorInterface.html#method_getName
3. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/DataCollector/DataCollectorInterface.html#method_collect
4. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/DataCollector/DataCollector.html
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
$this->data = array(
'method' => $request->getMethod(),
'acceptable_content_types' => $request->getAcceptableContentTypes(),
);
}
public function getMethod()
{
return $this->data['method'];
}
public function getAcceptableContentTypes()
{
return $this->data['acceptable_content_types'];
}
public function getName()
{
return 'app.request_collector';
}
}
The getters are added to give the template access to the collected information.
As the profiler serializes data collector instances, you should not store objects that cannot be
serialized (like PDO objects) or you need to provide your own serialize() method.
# app/config/services.yml
services:
app.request_collector:
class: AppBundle\DataCollector\RequestCollector
public: false
tags:
- { name: data_collector }
1
2
3
4
5
6
7
1
2
3
4
5
6
7
8
9
{% extends 'WebProfilerBundle:Profiler:layout.html.twig' %}
{% block toolbar %}
{% set icon %}
{# this is the content displayed as a panel in the toolbar #}
<span class="icon"><img src="..." alt=""/></span>
<span class="sf-toolbar-status">Request</span>
{% endset %}
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{% set text %}
{# this is the content displayed when hovering the mouse over
the toolbar panel #}
<div class="sf-toolbar-info-piece">
<b>Method</b>
<span>{{ collector.method }}</span>
</div>
<div class="sf-toolbar-info-piece">
<b>Accepted content type</b>
<span>{{ collector.acceptableContentTypes|join(', ') }}</span>
</div>
{% endset %}
{# the 'link' value set to 'false' means that this panel doesn't
show a section in the web profiler #}
{{ include('@WebProfiler/Profiler/toolbar_item.html.twig', { link: false }) }}
{% endblock %}
Built-in collector templates define all their images as embedded base64-encoded images. This makes
them work everywhere without having to mess with web assets links:
Listing 83-5
Another solution is to define the images as SVG files. In addition to being resolution-independent,
these images can be easily embedded in the Twig template or included from an external file to reuse
them in several templates:
Listing 83-6
{{ include('@App/data_collector/icon.svg') }}
You are encouraged to use the latter technique for your own toolbar panels.
If the toolbar panel includes extended web profiler information, the Twig template must also define
additional blocks:
Listing 83-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{% extends '@WebProfiler/Profiler/layout.html.twig' %}
{% block toolbar %}
{% set icon %}
<span class="icon"><img src="..." alt=""/></span>
<span class="sf-toolbar-status">Request</span>
{% endset %}
{% set text %}
<div class="sf-toolbar-info-piece">
{# ... #}
</div>
{% endset %}
{{ include('@WebProfiler/Profiler/toolbar_item.html.twig', { 'link': true }) }}
{% endblock %}
{% block head %}
{# Optional. Here you can link to or define your own CSS and JS contents. #}
{# Use {{ parent() }} to extend the default styles instead of overriding them. #}
{% endblock %}
{% block menu %}
{# This left-hand menu appears when using the full-screen profiler. #}
<span class="label">
<span class="icon"><img src="..." alt=""/></span>
<strong>Request</strong>
</span>
{% endblock %}
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
{% block panel %}
{# Optional, for showing the most details. #}
<h2>Acceptable Content Types</h2>
<table>
<tr>
<th>Content Type</th>
</tr>
{% for type in collector.acceptableContentTypes %}
<tr>
<td>{{ type }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
The menu and panel blocks are the only required blocks to define the contents displayed in the web
profiler panel associated with this data collector. All blocks have access to the collector object.
Finally, to enable the data collector template, add a template attribute to the data_collector tag in
your service configuration:
Listing 83-8
1
2
3
4
5
6
7
8
9
10
# app/config/services.yml
services:
app.request_collector:
class: AppBundle\DataCollector\RequestCollector
tags:
name:
data_collector
template: 'data_collector/template.html.twig'
id:
'app.request_collector'
public: false
The id attribute must match the value returned by the getName() method.
The position of each panel in the toolbar is determined by the priority defined by each collector. Most
built-in collectors use 255 as their priority. If you want your collector to be displayed before them, use a
higher value:
Listing 83-9
1
2
3
4
5
6
# app/config/services.yml
services:
app.request_collector:
class: AppBundle\DataCollector\RequestCollector
tags:
- { name: data_collector, template: '...', id: '...', priority: 300 }
Chapter 84
1
2
3
4
5
6
# app/config/config.yml
framework:
# ...
profiler:
matcher:
ip: 168.0.0.1
You can also set a path option to define the path on which the profiler should be enabled. For instance,
setting it to ^/admin/ will enable the profiler only for the URLs which start with /admin/.
Chapter 84: How to Use Matchers to Enable the Profiler Conditionally | 311
returns false when the request doesn't match the conditions and true otherwise. Therefore, the
custom matcher must return false to disable the profiler and true to enable it.
Suppose that the profiler must be enabled whenever a user with a ROLE_SUPER_ADMIN is logged in.
This is the only code needed for that custom matcher:
Listing 84-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Profiler/SuperAdminMatcher.php
namespace AppBundle\Profiler;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
class SuperAdminMatcher implements RequestMatcherInterface
{
protected $authorizationChecker;
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
public function matches(Request $request)
{
return $this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN');
}
}
New in version 2.6: The AuthorizationCheckerInterface4 was introduced in Symfony 2.6. Prior,
you had to use the isGranted method of SecurityContextInterface5.
Then, configure a new service and set it as private because the application won't use it directly:
Listing 84-3
1
2
3
4
5
6
# app/config/services.yml
services:
app.super_admin_matcher:
class: AppBundle\Profiler\SuperAdminMatcher
arguments: ['@security.authorization_checker']
public: false
1
2
3
4
5
6
# app/config/config.yml
framework:
# ...
profiler:
matcher:
service: app.super_admin_matcher
2. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/RequestMatcherInterface.html
3. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/RequestMatcherInterface.html#method_matches
4. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authorization/AuthorizationCheckerInterface.html
5. http://api.symfony.com/2.7/Symfony/Component/Security/Core/SecurityContextInterface.html
Chapter 84: How to Use Matchers to Enable the Profiler Conditionally | 312
Chapter 85
1
2
3
4
5
6
7
# app/config/config.yml
framework:
profiler:
dsn:
'mysql:host=localhost;dbname=%database_name%'
username: '%database_user%'
password: '%database_password%'
lifetime: 3600
The HttpKernel component currently supports the following profiler storage drivers:
file
sqlite
mysql
mongodb
memcache
memcached
redis
Chapter 86
When the profiler stores data about a request, it also associates a token with it; this token is available in
the X-Debug-Token HTTP header of the response. Using this token, you can access the profile of any
past response thanks to the loadProfile()2 method:
Listing 86-2
$token = $response->headers->get('X-Debug-Token');
$profile = $container->get('profiler')->loadProfile($token);
When the profiler is enabled but not the web debug toolbar, inspect the page with your browser's
developer tools to get the value of the X-Debug-Token HTTP header.
The profiler service also provides the find()3 method to look for tokens based on some criteria:
Listing 86-3
1
2
3
4
5
6
7
8
9
10
1. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Profiler/Profiler.html#method_loadProfileFromResponse
2. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Profiler/Profiler.html#method_loadProfile
3. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Profiler/Profiler.html#method_find
11
12
$tokens = $container->get('profiler')
->find('', '', 10, '', '4 days ago', '2 days ago');
Lastly, if you want to manipulate profiling data on a different machine than the one where the
information was generated, use the profiler:export and profiler:import commands:
Listing 86-4
1
2
3
4
5
6
7
8
Chapter 87
The PSR-7 bridge converts HttpFoundation objects from and to objects implementing HTTP
message interfaces defined by the PSR-71.
Installation
You can install the component in 2 different ways:
Install it via Composer (symfony/psr-http-message-bridge on Packagist2);
Use the official Git repository (https://github.com/symfony/psr-http-message-bridge).
The bridge also needs a PSR-7 implementation to allow converting HttpFoundation objects to PSR-7
objects. It provides native support for Zend Diactoros3. Use Composer (zendframework/zend-diactoros on
Packagist4) or refer to the project documentation to install it.
Usage
Converting from HttpFoundation Objects to PSR-7
The bridge provides an interface of a factory called HttpMessageFactoryInterface5 that builds
objects implementing PSR-7 interfaces from HttpFoundation objects. It also provide a default
implementation using Zend Diactoros internally.
1. http://www.php-fig.org/psr/psr-7/
2. https://packagist.org/packages/symfony/psr-http-message-bridge
3. https://github.com/zendframework/zend-diactoros
4. https://packagist.org/packages/zendframework/zend-diactoros
5. http://api.symfony.com/2.7/Symfony/Bridge/PsrHttpMessage/HttpMessageFactoryInterface.html
The following code snippet explain how to convert a Request6 to a Zend Diactoros ServerRequest7
implementing the ServerRequestInterface8 interface:
Listing 87-1
1
2
3
4
5
6
7
8
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Symfony\Component\HttpFoundation\Request;
$symfonyRequest = new Request(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'dunglas.fr'),
'Content');
// The HTTP_HOST server key must be set to avoid an unexpected error
$psr7Factory = new DiactorosFactory();
$psrRequest = $psr7Factory->createRequest($symfonyRequest);
And
now
from
a
11
ResponseInterface interface:
Listing 87-2
1
2
3
4
5
6
7
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Symfony\Component\HttpFoundation\Response;
$symfonyResponse = new Response('Content');
$psr7Factory = new DiactorosFactory();
$psrResponse = $psr7Factory->createResponse($symfonyResponse);
the
other
hand,
the
bridge
provide
factory
interface
called
1
2
3
4
5
6
ServerRequestInterface13
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
1
2
3
4
5
6
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
6. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html
7. http://api.symfony.com/2.7/Zend/Diactoros/ServerRequest.html
8. http://api.symfony.com/2.7/Psr/Http/Message/ServerRequestInterface.html
9. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Response.html
10. http://api.symfony.com/2.7/Zend/Diactoros/Response.html
11. http://api.symfony.com/2.7/Psr/Http/Message/ResponseInterface.html
12. http://api.symfony.com/2.7/Symfony/Bridge/PsrHttpMessage/HttpFoundationFactoryInterface.html
13. http://api.symfony.com/2.7/Psr/Http/Message/ServerRequestInterface.html
14. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html
15. http://api.symfony.com/2.7/Psr/Http/Message/ResponseInterface.html
16. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Response.html
Chapter 88
Solution: trusted_proxies
This is no problem, but you do need to tell Symfony what is happening and which reverse proxy IP
addresses will be doing this type of thing:
Listing 88-1
1
2
3
4
# app/config/config.yml
# ...
framework:
trusted_proxies: [192.0.0.1, 10.0.0.0/8]
In this example, you're saying that your reverse proxy (or proxies) has the IP address 192.0.0.1 or
matches the range of IP addresses that use the CIDR notation 10.0.0.0/8. For more details, see the
framework.trusted_proxies option.
You are also saying that you trust that the proxy does not send conflicting headers, e.g. sending both XForwarded-For and Forwarded in the same request.
Chapter 88: How to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy | 318
That's it! Symfony will now look for the correct headers to get information like the client's IP address,
host, port and whether the request is using HTTPS.
1
2
3
4
5
6
7
// web/app.php
// ...
Request::setTrustedProxies(array('127.0.0.1', $request->server->get('REMOTE_ADDR')));
$response = $kernel->handle($request);
// ...
3. Ensure that the trusted_proxies setting in your app/config/config.yml is not set or it will
overwrite the setTrustedProxies call above.
That's it! It's critical that you prevent traffic from all non-trusted sources. If you allow outside traffic, they
could "spoof" their true IP address and other information.
My Reverse Proxy Sends X-Forwarded-For but Does not Filter the Forwarded
Header
Many popular proxy implementations do not yet support the Forwarded header and do not filter it by
default. Ideally, you would configure this in your proxy. If this is not possible, you can tell Symfony to
distrust the Forwarded header, while still trusting your proxy's X-Forwarded-For header.
This is done inside of your front controller:
Listing 88-3
1
2
3
4
5
6
7
// web/app.php
// ...
Request::setTrustedHeaderName(Request::HEADER_FORWARDED, null);
$response = $kernel->handle($request);
// ...
Configuring the proxy server trust is very important, as not doing so will allow malicious users to "spoof"
their IP address.
1. http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-elb-security-groups.html
2. http://tools.ietf.org/html/rfc7239
Chapter 88: How to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy | 319
But if your reverse proxy uses other non-standard header names, you can configure these (see "Trusting
Proxies").
The code for doing this will need to live in your front controller (e.g. web/app.php).
Chapter 88: How to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy | 320
Chapter 89
1
2
3
4
5
# app/config/config.yml
framework:
request:
formats:
jsonp: 'application/javascript'
You can also associate multiple mime types to a format, but please note that the preferred one must
be the first as it will be used as the content type:
Listing 89-2
1
2
3
4
5
# app/config/config.yml
framework:
request:
formats:
csv: ['text/csv', 'text/plain']
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html#method_getRequestFormat
Chapter 89: How to Register a new Request Format and Mime Type | 321
Chapter 90
1
2
3
4
secure:
path:
/secure
defaults: { _controller: AppBundle:Main:secure }
schemes: [https]
The above configuration forces the secure route to always use HTTPS.
When generating the secure URL, and if the current scheme is HTTP, Symfony will automatically
generate an absolute URL with HTTPS as the scheme:
Listing 90-2
1
2
3
4
5
6
7
The requirement is also enforced for incoming requests. If you try to access the /secure path with
HTTP, you will automatically be redirected to the same URL, but with the HTTPS scheme.
The above example uses https for the scheme, but you can also force a URL to always use http.
The Security component provides another way to enforce HTTP or HTTPS via the
requires_channel setting. This alternative method is better suited to secure an "area" of your
website (all URLs under /admin) or when you want to secure URLs defined in a third party bundle
(see How to Force HTTPS or HTTP for different URLs for more details).
Chapter 90: How to Force Routes to always Use HTTPS or HTTP | 322
Chapter 91
1
2
3
4
5
6
7
8
9
10
11
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DemoController
{
/**
* @Route("/hello/{username}", name="_hello", requirements={"username"=".+"})
*/
public function helloAction($username)
{
// ...
}
}
That's it! Now, the {username} parameter can contain the / character.
Chapter 92
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/config/routing.yml
# load some routes - one should ultimately have the path "/app"
AppBundle:
resource: '@AppBundle/Controller/'
type:
annotation
prefix: /app
# redirecting the root
root:
path: /
defaults:
_controller: FrameworkBundle:Redirect:urlRedirect
path: /app
permanent: true
In this example, you configured a route for the / path and let the RedirectController redirect it to
/app. The permanent switch tells the action to issue a 301 HTTP status code instead of the default
302 HTTP status code.
1. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.html
2. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.html#method_urlRedirectAction
1
2
3
4
5
6
7
8
9
10
11
# app/config/routing.yml
# ...
# redirecting the admin home
root:
path: /wp-admin
defaults:
_controller: FrameworkBundle:Redirect:redirect
route: sonata_admin_dashboard
permanent: true
Because you are redirecting to a route instead of a path, the required option is called route in the
redirect action, instead of path in the urlRedirect action.
3. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.html#method_redirectAction
Chapter 93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
blog_show:
path:
/blog/{slug}
defaults: { _controller: AppBundle:Blog:show }
methods: [GET]
blog_update:
path:
/blog/{slug}
defaults: { _controller: AppBundle:Blog:update }
methods: [PUT]
blog_delete:
path:
/blog/{slug}
defaults: { _controller: AppBundle:Blog:delete }
methods: [DELETE]
Chapter 93: How to Use HTTP Methods beyond GET and POST in Routes | 326
You can disable the _method functionality shown here using the http_method_override option.
Chapter 93: How to Use HTTP Methods beyond GET and POST in Routes | 327
Chapter 94
1
2
3
4
5
6
# app/config/routing.yml
contact:
path:
/{_locale}/contact
defaults: { _controller: AppBundle:Main:contact }
requirements:
_locale: '%app.locales%'
You can now control and set the app.locales parameter somewhere in your container:
Listing 94-2
1
2
3
# app/config/config.yml
parameters:
app.locales: en|es
You can also use a parameter to define your route path (or part of your path):
Listing 94-3
1
2
3
4
# app/config/routing.yml
some_route:
path:
/%app.route_prefix%/contact
defaults: { _controller: AppBundle:Main:contact }
Just like in normal service container configuration files, if you actually need a % in your route,
you can escape the percent sign by doubling it, e.g. /score-50%%, which would resolve to
/score-50%.
However, as the % characters included in any URL are automatically encoded, the resulting URL of
this example would be /score-50%25 (%25 is the result of encoding the % character).
Chapter 94: How to Use Service Container Parameters in your Routes | 328
For parameter handling within a Dependency Injection Class see Using Parameters within a Dependency
Injection Class.
Chapter 94: How to Use Service Container Parameters in your Routes | 329
Chapter 95
Loading Routes
The routes in a Symfony application are loaded by the DelegatingLoader6. This loader uses several
other loaders (delegates) to load resources of different types, for instance YAML files or @Route and
@Method annotations in controller files. The specialized loaders implement LoaderInterface7 and
therefore have two important methods: supports()8 and load()9.
Take these lines from the routing.yml in the Symfony Standard Edition:
1.
2.
3.
4.
5.
https://github.com/FriendsOfSymfony/FOSRestBundle
https://github.com/FriendsOfSymfony/FOSRestBundle
https://github.com/schmittjoh/JMSI18nRoutingBundle
https://github.com/KnpLabs/KnpRadBundle
https://github.com/sonata-project/SonataAdminBundle
6. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.html
7. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html
8. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html#method_supports
9. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html#method_load
Listing 95-1
1
2
3
4
# app/config/routing.yml
app:
resource: '@AppBundle/Controller/'
type:
annotation
When the main loader parses this, it tries all registered delegate loaders and calls their supports()10
method with the given resource (@AppBundle/Controller/) and type (annotation) as arguments.
When one of the loader returns true, its load()11 method will be called, which should return a
RouteCollection12 containing Route13 objects.
Routes loaded this way will be cached by the Router the same way as when they are defined in one
of the default formats (e.g. XML, YML, PHP file).
The sample loader below supports loading routing resources with a type of extra. The type name
should not clash with other loaders that might support the same type of resource. Just make up a name
specific to what you do. The resource name itself is not actually used in the example:
Listing 95-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/AppBundle/Routing/ExtraLoader.php
namespace AppBundle\Routing;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class ExtraLoader extends Loader
{
private $loaded = false;
public function load($resource, $type = null)
{
if (true === $this->loaded) {
throw new \RuntimeException('Do not add the "extra" loader twice');
}
$routes = new RouteCollection();
10. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html#method_supports
11. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html#method_load
12. http://api.symfony.com/2.7/Symfony/Component/Routing/RouteCollection.html
13. http://api.symfony.com/2.7/Symfony/Component/Routing/Route.html
14. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html
15. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/Loader.html
16. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
);
$route = new Route($path, $defaults, $requirements);
Make sure the controller you specify really exists. In this case you have to create an extraAction
method in the ExtraController of the AppBundle:
Listing 95-3
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/AppBundle/Controller/ExtraController.php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ExtraController extends Controller
{
public function extraAction($parameter)
{
return new Response($parameter);
}
}
1
2
3
4
5
6
# app/config/services.yml
services:
app.routing_loader:
class: AppBundle\Routing\ExtraLoader
tags:
- { name: routing.loader }
Notice the tag routing.loader. All services with this tag will be marked as potential route loaders
and added as specialized route loaders to the routing.loader service, which is an instance of
DelegatingLoader17.
1
2
3
4
# app/config/routing.yml
app_extra:
resource: .
type: extra
17. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.html
The important part here is the type key. Its value should be "extra" as this is the type which the
ExtraLoader supports and this will make sure its load() method gets called. The resource key is
insignificant for the ExtraLoader, so it is set to ".".
The routes defined using custom route loaders will be automatically cached by the framework. So
whenever you change something in the loader class itself, don't forget to clear the cache.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Routing/AdvancedLoader.php
namespace AppBundle\Routing;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\RouteCollection;
class AdvancedLoader extends Loader
{
public function load($resource, $type = null)
{
$collection = new RouteCollection();
$resource = '@AppBundle/Resources/config/import_routing.yml';
$type = 'yaml';
$importedRoutes = $this->import($resource, $type);
$collection->addCollection($importedRoutes);
return $collection;
}
public function supports($resource, $type = null)
{
return 'advanced_extra' === $type;
}
}
The resource name and type of the imported routing configuration can be anything that would
normally be supported by the routing configuration loader (YAML, XML, PHP, annotation, etc.).
18. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/Loader.html
19. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderResolver.html
20. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html#method_supports
21. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/LoaderInterface.html#method_load
22. http://api.symfony.com/2.7/Symfony/Component/Config/Loader/Loader.html#method_import
Chapter 96
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Controller/RedirectingController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class RedirectingController extends Controller
{
public function removeTrailingSlashAction(Request $request)
{
$pathInfo = $request->getPathInfo();
$requestUri = $request->getRequestUri();
$url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $requestUri);
return $this->redirect($url, 301);
}
}
After that, create a route to this controller that's matched whenever a URL with a trailing slash is
requested. Be sure to put this route last in your system, as explained below:
Listing 96-2
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/AppBundle/Controller/RedirectingController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class RedirectingController extends Controller
{
/**
* @Route("/{url}", name="remove_trailing_slash",
*
requirements={"url" = ".*\/$"}, methods={"GET"})
*/
public function removeTrailingSlashAction(Request $request)
14
15
16
17
// ...
}
}
Redirecting a POST request does not work well in old browsers. A 302 on a POST request would
send a GET request after the redirection for legacy reasons. For that reason, the route here only
matches GET requests.
Make sure to include this route in your routing configuration at the very end of your route listing.
Otherwise, you risk redirecting real routes (including Symfony core routes) that actually do have a
trailing slash in their path.
Chapter 97
1
2
3
4
5
6
7
# app/config/routing.yml
blog:
path:
/blog/{page}
defaults:
_controller: AppBundle:Blog:index
page:
1
title:
"Hello world!"
Now, you can access this extra parameter in your controller, as an argument to the controller method:
Listing 97-2
1
2
3
4
5
6
7
8
use Symfony\Component\HttpFoundation\Request;
public function indexAction(Request $request, $page)
{
$title = $request->attributes->get('title');
// ...
}
As you can see, the $title variable was never defined inside the route path, but you can still access
its value from inside your controller, through the method's argument, or from the Request object's
attributes bag.
Chapter 97: How to Pass Extra Information from a Route to a Controller | 336
Chapter 98
1. https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
2. http://symfony.com/doc/master/cmf/book/routing.html
Chapter 98: Looking up Routes from a Database: Symfony CMF DynamicRouter | 337
Chapter 99
If you need a login form and are storing users in some sort of a database, then you should consider
using FOSUserBundle1, which helps you build your User object and gives you many routes and
controllers for common tasks like login, registration and forgot password.
In this entry, you'll build a traditional login form. Of course, when the user logs in, you can load your
users from anywhere - like the database. See B) Configuring how Users are Loaded for details.
First, enable form login under your firewall:
Listing 99-1
1
2
3
4
5
6
7
8
9
10
# app/config/security.yml
security:
# ...
firewalls:
main:
anonymous: ~
form_login:
login_path: login
check_path: login
The login_path and check_path can also be route names (but cannot have mandatory wildcards
- e.g. /login/{foo} where foo has no default value).
Now, when the security system initiates the authentication process, it will redirect the user to the
login form /login. Implementing this login form visually is your job. First, create a new
SecurityController inside a bundle:
Listing 99-2
1
2
3
4
5
6
// src/AppBundle/Controller/SecurityController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SecurityController extends Controller
1. https://github.com/FriendsOfSymfony/FOSUserBundle
7
8
{
}
Next, configure the route that you earlier used under your form_login configuration (login):
Listing 99-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/AppBundle/Controller/SecurityController.php
// ...
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class SecurityController extends Controller
{
/**
* @Route("/login", name="login")
*/
public function loginAction(Request $request)
{
}
}
Great! Next, add the logic to loginAction that will display the login form:
Listing 99-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Controller/SecurityController.php
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
in
version
2.6:
The
security.authentication_utils
AuthenticationUtils2 class were introduced in Symfony 2.6.
New
service
and
the
Don't let this controller confuse you. As you'll see in a moment, when the user submits the form, the
security system automatically handles the form submission for you. If the user had submitted an invalid
username or password, this controller reads the form submission error from the security system so that it
can be displayed back to the user.
In other words, your job is to display the login form and any login errors that may have occurred, but the
security system itself takes care of checking the submitted username and password and authenticating
the user.
Finally, create the template:
Listing 99-5
1
2
3
4
{# app/Resources/views/security/login.html.twig #}
{# ... you will probably extends your base template, like base.html.twig #}
{% if error %}
2. http://api.symfony.com/2.7/Symfony/Component/Security/Http/Authentication/AuthenticationUtils.html
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{#
If you want to control the URL the user
is redirected to on success (more details below)
<input type="hidden" name="_target_path" value="/account" />
#}
<button type="submit">login</button>
</form>
The form can look like anything, but has a few requirements:
The form must POST to the login route, since that's what you configured under the form_login key in
security.yml.
The username must have the name _username and the password must have the name _password.
Actually, all of this can be configured under the form_login key. See Form Login Configuration
for more details.
This login form is currently not protected against CSRF attacks. Read Using CSRF Protection in the
Login Form on how to protect your login form.
And that's it! When you submit the form, the security system will automatically check the user's
credentials and either authenticate the user or send the user back to the login form where the error can
be displayed.
To review the whole process:
1. The user tries to access a resource that is protected;
2. The firewall initiates the authentication process by redirecting the user to the login form (/login);
3. The /login page renders login form via the route and controller created in this example;
4. The user submits the login form to /login;
5. The security system intercepts the request, checks the user's submitted credentials,
authenticates the user if they are correct, and sends the user back to the login form if they are
not.
For more details on this and how to customize the form login process in general, see How to Customize
your Form Login.
1
2
3
4
5
# app/config/security.yml
# ...
access_control:
- { path: ^/, roles: ROLE_ADMIN }
Adding an access control that matches /login/* and requires no authentication fixes the problem:
Listing 99-7
1
2
3
4
5
6
# app/config/security.yml
# ...
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_ADMIN }
Also, if your firewall does not allow for anonymous users (no anonymous key), you'll need to create a
special firewall that allows anonymous users for the login page:
Listing 99-8
1
2
3
4
5
6
7
8
9
10
11
# app/config/security.yml
# ...
firewalls:
# order matters! This must be before the ^/ firewall
login_firewall:
pattern:
^/login$
anonymous: ~
secured_area:
pattern:
^/
form_login: ~
Chapter 100
Introduction
Before you start, you should check out FOSUserBundle1. This external bundle allows you to load
users from the database (like you'll learn here) and gives you built-in routes & controllers for things
like login, registration and forgot password. But, if you need to heavily customize your user system
or if you want to learn how things work, this tutorial is even better.
1
2
3
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
1. https://github.com/FriendsOfSymfony/FOSUserBundle
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 343
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @ORM\Table(name="app_users")
* @ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* @ORM\Column(type="string", length=64)
*/
private $password;
/**
* @ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct()
{
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 344
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
To make things shorter, some of the getter and setter methods aren't shown. But you can generate these
by running:
Listing 100-2
getRoles()3
getPassword()4
getSalt()5
getUsername()6
eraseCredentials()7
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getRoles
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getPassword
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getSalt
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getUsername
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_eraseCredentials
8. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 345
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# app/config/security.yml
security:
encoders:
AppBundle\Entity\User:
algorithm: bcrypt
# ...
providers:
our_db_provider:
entity:
class: AppBundle:User
property: username
# if you're using multiple entity managers
# manager_name: customer
firewalls:
main:
pattern:
^/
http_basic: ~
provider: our_db_provider
# ...
First, the encoders section tells Symfony to expect that the passwords in the database will be encoded
using bcrypt. Second, the providers section creates a "user provider" called our_db_provider
that knows to query from your AppBundle:User entity by the username property. The name
our_db_provider isn't important: it just needs to match the value of the provider key under
your firewall. Or, if you don't set the provider key under your firewall, the first "user provider" is
automatically used.
If you're using PHP 5.4 or lower, you'll need to install the ircmaxell/password-compat library
via Composer in order to be able to use the bcrypt encoder:
Listing 100-5
1
2
3
9. https://symfony.com/doc/master/bundles/DoctrineFixturesBundle/index.html
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 346
4
5
6
+----+----------+--------------------------------------------------------------+--------------------+-----------+
| 1 | admin
| $2a$08$jHZj/wJfcVKlIwr5AvR78euJxYK7Ku5kURNhNx.7.CSIJ3Pq6LEPC | [email protected] |
1 |
+----+----------+--------------------------------------------------------------+--------------------+-----------+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
AdvancedUserInterface10. This
// src/AppBundle/Entity/User.php
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
// ...
class User implements AdvancedUserInterface, \Serializable
{
// ...
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
10. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/AdvancedUserInterface.html
11. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 347
40
41
42
43
44
45
list (
// ...
$this->isActive
) = unserialize($serialized);
}
}
The AdvancedUserInterface12 interface adds four extra methods to validate the account status:
If any of these return false, the user won't be allowed to login. You can choose to have persisted
properties for all of these, or whatever you need (in this example, only isActive pulls from the
database).
So what's the difference between the methods? Each returns a slightly different error message (and these
can be translated when you render them in your login template to customize them further).
If you use AdvancedUserInterface, you also need to add any of the properties used by these
methods (like isActive) to the serialize() and unserialize() methods. If you don't do
this, your user may not be deserialized correctly from the session on each request.
Congrats! Your database-loading security system is all setup! Next, add a true login form instead of HTTP
Basic or keep reading for other topics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
12.
13.
14.
15.
16.
// src/AppBundle/Entity/UserRepository.php
namespace AppBundle\Entity;
use
use
use
use
Symfony\Component\Security\Core\User\UserInterface;
Symfony\Component\Security\Core\User\UserProviderInterface;
Symfony\Component\Security\Core\Exception\UnsupportedUserException;
Doctrine\ORM\EntityRepository;
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/AdvancedUserInterface.html
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/AdvancedUserInterface.html#method_isAccountNonExpired
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/AdvancedUserInterface.html#method_isAccountNonLocked
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/AdvancedUserInterface.html#method_isCredentialsNonExpired
http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/AdvancedUserInterface.html#method_isEnabled
17. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserProviderInterface.html
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 348
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
->getQuery()
->getOneOrNullResult();
}
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}
return $this->find($user->getId());
}
public function supportsClass($class)
{
return $this->getEntityName() === $class
|| is_subclass_of($class, $this->getEntityName());
}
}
To finish this, just remove the property key from the user provider in security.yml:
Listing 100-9
1
2
3
4
5
6
7
8
# app/config/security.yml
security:
# ...
providers:
our_db_provider:
entity:
class: AppBundle:User
This tells Symfony to not query automatically for the User. Instead, when someone logs in, the
loadUserByUsername() method on UserRepository will be called.
18. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserProviderInterface.html
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 349
First, the Serializable19 interface and its serialize and unserialize methods have been added
to allow the User class to be serialized to the session. This may or may not be needed depending on
your setup, but it's probably a good idea. In theory, only the id needs to be serialized, because the
refreshUser()20 method refreshes the user on each request by using the id (as explained above). This
gives us a "fresh" User object.
But Symfony also uses the username, salt, and password to verify that the User has not changed
between requests (it also calls your AdvancedUserInterface methods if you implement it). Failing
to serialize these may cause you to be logged out on each request. If your User implements the
EquatableInterface21, then instead of these properties being checked, your isEqualTo method
is simply called, and you can check whatever properties you want. Unless you understand this, you
probably won't need to implement this interface or worry about it.
19. http://php.net/manual/en/class.serializable.php
20. http://api.symfony.com/2.7/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.html#method_refreshUser
21. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/EquatableInterface.html
Chapter 100: How to Load Security Users from the Database (the Entity Provider) | 350
Chapter 101
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/config/security.yml
security:
# ...
firewalls:
main:
# ...
remember_me:
key:
'%secret%'
lifetime: 604800 # 1 week in seconds
path:
/
# by default, the feature is enabled by checking a
# checkbox in the login form (see below), uncomment the
# following line to always enable it.
#always_remember_me: true
secret
name (default
value: REMEMBERME)
The name of the cookie used to keep the user logged in. If you enable the remember_me feature in
several firewalls of the same application, make sure to choose a different name for the cookie of each
firewall. Otherwise, you'll face lots of security related problems.
lifetime (default
value: 31536000)
The number of seconds during which the user will remain logged in. By default users are logged in
for one year.
path (default
value: /)
The path where the cookie associated with this feature is used. By default the cookie will be applied
to the entire website but you can restrict to a specific section (e.g. /forum, /admin).
domain (default
value: null)
The domain where the cookie associated with this feature is used. By default cookies use the current
domain obtained from $_SERVER.
secure (default
value: false)
If true, the cookie associated with this feature is sent to the user through an HTTPS secure
connection.
httponly (default
value: true)
If true, the cookie associated with this feature is accessible only through the HTTP protocol. This
means that the cookie won't be accessible by scripting languages, such as JavaScript.
remember_me_parameter (default
value: _remember_me)
The name of the form field checked to decide if the "Remember Me" feature should be enabled or
not. Keep reading this article to know how to enable this feature conditionally.
always_remember_me (default
value: false)
If true, the value of the remember_me_parameter is ignored and the "Remember Me" feature is always
enabled, regardless of the desire of the end user.
token_provider (default
value: null)
Defines the service id of a token provider to use. By default, tokens are stored in a cookie.
For example, you might want to store the token in a database, to not have a (hashed) version
of
the
password
in
a
cookie.
The
DoctrineBridge
comes
with
a
Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider that you can use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{# app/Resources/views/security/login.html.twig #}
{% if error %}
<div>{{ error.message }}</div>
{% endif %}
<form action="{{ path('login') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<input type="checkbox" id="remember_me" name="_remember_me" checked />
<label for="remember_me">Keep me logged in</label>
<input type="submit" name="login" />
</form>
The user will then automatically be logged in on subsequent visits while the cookie remains valid.
Automatically assigned to a user who is in a firewall protected part of the site but who has not
actually logged in. This is only possible if anonymous access has been allowed.
IS_AUTHENTICATED_REMEMBERED
Automatically assigned to a user that has provided their login details during the current session.
You can use these to control access beyond the explicitly assigned roles.
you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the
IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role,
If
then you also have the other two roles. In other words, these roles represent three levels of increasing
"strength" of authentication.
You can use these additional roles for finer grained control over access to parts of a site. For example,
you may want your user to be able to view their account at /account when authenticated by cookie but
to have to provide their login details to be able to edit the account details. You can do this by securing
specific controller actions using these roles. The edit action in the controller could be secured using the
service context.
In the following example, the action is only allowed if the user has the IS_AUTHENTICATED_FULLY
role.
Listing 101-3
1
2
3
4
5
6
7
8
9
10
// ...
use Symfony\Component\Security\Core\Exception\AccessDeniedException
// ...
public function editAction()
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
// ...
}
If your application is based on the Symfony Standard Edition, you can also secure your controller using
annotations:
Listing 101-4
1
2
3
4
5
6
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
/**
* @Security("has_role('IS_AUTHENTICATED_FULLY')")
*/
public function editAction($name)
{
8
9
// ...
}
If you also had an access control in your security configuration that required the user to have a
ROLE_USER role in order to access any of the account area, then you'd have the following situation:
If a non-authenticated (or anonymously authenticated user) tries to access the account area,
the user will be asked to authenticate.
Once the user has entered their username and password, assuming the user receives the
ROLE_USER role per your configuration, the user will have the IS_AUTHENTICATED_FULLY role and be able
to access any page in the account section, including the editAction controller.
If the user's session ends, when the user returns to the site, they will be able to access every
account page - except for the edit page - without being forced to re-authenticate. However,
when they try to access the editAction controller, they will be forced to re-authenticate, since
they are not, yet, fully authenticated.
For more information on securing services or methods in this way, see How to Secure any Service or
Method in your Application.
Chapter 102
Impersonating the user can be easily done by activating the switch_user firewall listener:
Listing 102-1
1
2
3
4
5
6
7
8
# app/config/security.yml
security:
# ...
firewalls:
main:
# ...
switch_user: true
To switch to another user, just add a query string with the _switch_user parameter and the username
as the value to the current URL:
Listing 102-2
http://example.com/somewhere?_switch_user=thomas
To switch back to the original user, use the special _exit username:
Listing 102-3
http://example.com/somewhere?_switch_user=_exit
During impersonation, the user is provided with a special role called ROLE_PREVIOUS_ADMIN. In a
template, for instance, this role can be used to show a link to exit impersonation:
Listing 102-4
1
2
3
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
<a href="{{ path('homepage', {'_switch_user': '_exit'}) }}">Exit impersonation</a>
{% endif %}
In some cases you may need to get the object that represents the impersonating user rather than the
impersonated user. Use the following snippet to iterate over the user's roles until you find one that a
SwitchUserRole object:
Listing 102-5
1
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\Security\Core\Role\SwitchUserRole;
$authChecker = $this->get('security.authorization_checker');
$tokenStorage = $this->get('security.token_storage');
if ($authChecker->isGranted('ROLE_PREVIOUS_ADMIN')) {
foreach ($tokenStorage->getToken()->getRoles() as $role) {
if ($role instanceof SwitchUserRole) {
$impersonatingUser = $role->getSource()->getUser();
break;
}
}
}
Of course, this feature needs to be made available to a small group of users. By default, access is restricted
to users having the ROLE_ALLOWED_TO_SWITCH role. The name of this role can be modified via the
role setting. For extra security, you can also change the query parameter name via the parameter
setting:
Listing 102-6
# app/config/security.yml
security:
# ...
1
2
3
4
5
6
7
8
firewalls:
main:
# ...
switch_user: { role: ROLE_ADMIN, parameter: _want_to_be_this_user }
Events
The firewall dispatches the security.switch_user event right after the impersonation is completed.
The SwitchUserEvent1 is passed to the listener, and you can use this to get the user that you are now
impersonating.
The cookbook article about Making the Locale "Sticky" during a User's Session does not update the locale
when you impersonate a user. The following code sample will show how to change the sticky locale:
Listing 102-7
# app/config/services.yml
services:
app.switch_user_listener:
class: AppBundle\EventListener\SwitchUserListener
tags:
- { name: kernel.event_listener, event: security.switch_user, method: onSwitchUser }
1
2
3
4
5
6
The listener implementation assumes your User entity has a getLocale() method.
Listing 102-8
1
2
3
4
// src/AppBundle/EventListener/SwitchUserListener.php
namespace AppBundle\EventListener;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
1. http://api.symfony.com/2.7/Symfony/Component/Security/Http/Event/SwitchUserEvent.html
5
6
7
8
9
10
11
12
13
14
15
class SwitchUserListener
{
public function onSwitchUser(SwitchUserEvent $event)
{
$event->getRequest()->getSession()->set(
'_locale',
$event->getTargetUser()->getLocale()
);
}
}
Chapter 103
Listing 103-1
1
2
3
4
5
6
7
8
9
# app/config/security.yml
security:
# ...
firewalls:
main:
form_login:
# ...
default_target_path: default_security_target
Now, when no URL is set in the session, users will be sent to the default_security_target route.
1
2
3
4
5
6
7
8
9
# app/config/security.yml
security:
# ...
firewalls:
main:
form_login:
# ...
always_use_default_target_path: true
1
2
3
4
5
6
7
8
9
10
# app/config/security.yml
security:
# ...
firewalls:
main:
# ...
form_login:
# ...
use_referer: true
1
2
3
4
5
6
7
8
9
10
{# src/AppBundle/Resources/views/Security/login.html.twig #}
{% if error %}
<div>{{ error.message }}</div>
{% endif %}
<form action="{{ path('login') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
11
12
13
14
15
16
Now, the user will be redirected to the value of the hidden form field. The value attribute can be a relative
path, absolute URL, or a route name. You can even change the name of the hidden form field by changing
the target_path_parameter option to another value.
Listing 103-5
1
2
3
4
5
6
7
8
9
# app/config/security.yml
security:
# ...
firewalls:
main:
# ...
form_login:
target_path_parameter: redirect_url
1
2
3
4
5
6
7
8
9
10
# app/config/security.yml
security:
# ...
firewalls:
main:
# ...
form_login:
# ...
failure_path: login_failure
Chapter 104
1
2
3
4
// src/AppBundle/Security/User/WebserviceUser.php
namespace AppBundle\Security\User;
use Symfony\Component\Security\Core\User\UserInterface;
1. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getRoles
3. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getPassword
4. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getSalt
5. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_getUsername
6. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/UserInterface.html#method_eraseCredentials
7. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/EquatableInterface.html
8. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/EquatableInterface.html#method_isEqualTo
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use Symfony\Component\Security\Core\User\EquatableInterface;
class WebserviceUser implements UserInterface, EquatableInterface
{
private $username;
private $password;
private $salt;
private $roles;
public function __construct($username, $password, $salt, array $roles)
{
$this->username = $username;
$this->password = $password;
$this->salt = $salt;
$this->roles = $roles;
}
public function getRoles()
{
return $this->roles;
}
public function getPassword()
{
return $this->password;
}
public function getSalt()
{
return $this->salt;
}
public function getUsername()
{
return $this->username;
}
public function eraseCredentials()
{
}
public function isEqualTo(UserInterface $user)
{
if (!$user instanceof WebserviceUser) {
return false;
}
if ($this->password !== $user->getPassword()) {
return false;
}
if ($this->salt !== $user->getSalt()) {
return false;
}
if ($this->username !== $user->getUsername()) {
return false;
}
return true;
}
}
If you have more information about your users - like a "first name" - then you can add a firstName field
to hold that data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/AppBundle/Security/User/WebserviceUserProvider.php
namespace AppBundle\Security\User;
use
use
use
use
Symfony\Component\Security\Core\User\UserProviderInterface;
Symfony\Component\Security\Core\User\UserInterface;
Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
Symfony\Component\Security\Core\Exception\UnsupportedUserException;
// ...
return new WebserviceUser($username, $password, $salt, $roles);
}
throw new UsernameNotFoundException(
sprintf('Username "%s" does not exist.', $username)
);
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof WebserviceUser) {
throw new UnsupportedUserException(
sprintf('Instances of "%s" are not supported.', get_class($user))
);
}
return $this->loadUserByUsername($user->getUsername());
}
public function supportsClass($class)
{
return $class === 'AppBundle\Security\User\WebserviceUser';
}
}
Listing 104-3
1
2
3
4
# app/config/services.yml
services:
app.webservice_user_provider:
class: AppBundle\Security\User\WebserviceUserProvider
The real implementation of the user provider will probably have some dependencies or configuration
options or other services. Add these as arguments in the service definition.
Make sure the services file is being imported. See Importing Configuration with imports for details.
Modify security.yml
Everything comes together in your security configuration. Add the user provider to the list of providers
in the "security" section. Choose a name for the user provider (e.g. "webservice") and mention the id of
the service you just defined.
Listing 104-4
1
2
3
4
5
6
7
# app/config/security.yml
security:
# ...
providers:
webservice:
id: app.webservice_user_provider
Symfony also needs to know how to encode passwords that are supplied by website users, e.g. by filling
in a login form. You can do this by adding a line to the "encoders" section in your security configuration:
Listing 104-5
1
2
3
4
5
6
# app/config/security.yml
security:
# ...
encoders:
AppBundle\Security\User\WebserviceUser: bcrypt
The value here should correspond with however the passwords were originally encoded when creating
your users (however those users were created). When a user submits their password, it's encoded using
this algorithm and the result is compared to the hashed password returned by your getPassword()
method.
$password.'{'.$salt.'}'
If your external users have their passwords salted via a different method, then you'll need to do
a bit more work so that Symfony properly encodes the password. That is beyond the scope of
this entry, but would include sub-classing MessageDigestPasswordEncoder and overriding the
mergePasswordAndSalt method.
Additionally, you can configure the details of the algorithm used to hash passwords. In this example,
the application sets explicitly the cost of the bcrypt hashing:
Listing 104-7
1
2
3
4
5
6
7
8
# app/config/security.yml
security:
# ...
encoders:
AppBundle\Security\User\WebserviceUser:
algorithm: bcrypt
cost: 12
Chapter 105
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/Acme/HelloBundle/Security/TimeAuthenticator.php
namespace Acme\HelloBundle\Security;
use
use
use
use
use
use
use
use
Symfony\Component\HttpFoundation\Request;
Symfony\Component\Security\Core\Authentication\SimpleFormAuthenticatorInterface;
Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
Symfony\Component\Security\Core\Exception\AuthenticationException;
Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
Symfony\Component\Security\Core\User\UserProviderInterface;
1. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/SimpleFormAuthenticatorInterface.html
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
How it Works
Great! Now you just need to setup some Configuration. But first, you can find out more about what each
method in this class does.
1) createToken
When Symfony begins handling a request, createToken() is called, where you create a
TokenInterface2 object that contains whatever information you need in authenticateToken() to
authenticate the user (e.g. the username and password).
Whatever token object you create here will be passed to you later in authenticateToken().
2) supportsToken
After Symfony calls createToken(), it will then call supportsToken() on your class (and any other
authentication listeners) to figure out who should handle the token. This is just a way to allow several
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.html
authentication mechanisms to be used for the same firewall (that way, you can for instance first try to
authenticate the user via a certificate or an API key and fall back to a form login).
Mostly, you just need to make sure that this method returns true for a token that has been created by
createToken(). Your logic should probably look exactly like this example.
3) authenticateToken
If supportsToken returns true, Symfony will now call authenticateToken(). Your job here is to
check that the token is allowed to log in by first getting the User object via the user provider and then,
by checking the password and the current time.
The "flow" of how you get the User object and determine whether or not the token is valid (e.g.
checking the password), may vary based on your requirements.
Ultimately, your job is to return a new token object that is "authenticated" (i.e. it has at least 1 role set on
it) and which has the User object inside of it.
Inside this method, the password encoder is needed to check the password's validity:
Listing 105-2
This is a service that is already available in Symfony and it uses the password algorithm that is configured
in the security configuration (e.g. security.yml) under the encoders key. Below, you'll see how to
inject that into the TimeAuthenticator.
Configuration
Now, configure your TimeAuthenticator as a service:
Listing 105-3
1
2
3
4
5
6
7
# app/config/config.yml
services:
# ...
time_authenticator:
class:
Acme\HelloBundle\Security\TimeAuthenticator
arguments: ["@security.password_encoder"]
Then, activate it in the firewalls section of the security configuration using the simple_form key:
Listing 105-4
1
2
3
4
5
6
7
8
9
10
11
12
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
pattern: ^/admin
# ...
simple_form:
authenticator: time_authenticator
check_path:
login_check
login_path:
login
The simple_form key has the same options as the normal form_login option, but with the additional
authenticator key that points to the new service. For details, see Form Login Configuration.
If creating a login form in general is new to you or you don't understand the check_path or
login_path options, see How to Customize your Form Login.
PDF brought to you by
generated on July 28, 2016
Chapter 106
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/Security/ApiKeyAuthenticator.php
namespace AppBundle\Security;
use
use
use
use
use
use
use
Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
Symfony\Component\Security\Core\Exception\AuthenticationException;
Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
Symfony\Component\HttpFoundation\Request;
Symfony\Component\Security\Core\User\UserProviderInterface;
Symfony\Component\Security\Core\Exception\BadCredentialsException;
1. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/SimplePreAuthenticatorInterface.html
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Once you've configured everything, you'll be able to authenticate by adding an apikey parameter to
the
query
string,
like
http://example.com/api/
foo?apikey=37b51d194a7513e45b56f6524f2d51f2.
The authentication process has several steps, and your implementation will probably differ:
1. createToken
Early in the request cycle, Symfony calls createToken(). Your job here is to create a token object that
contains all of the information from the request that you need to authenticate the user (e.g. the apikey
query parameter). If that information is missing, throwing a BadCredentialsException2 will cause
authentication to fail. You might want to return null instead to just skip the authentication, so Symfony
can fallback to another authentication method, if any.
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Exception/BadCredentialsException.html
In case you return null from your createToken() method, be sure to enable anonymous in you
firewall. This way you'll be able to get an AnonymousToken.
2. supportsToken
After Symfony calls createToken(), it will then call supportsToken() on your class (and any other
authentication listeners) to figure out who should handle the token. This is just a way to allow several
authentication mechanisms to be used for the same firewall (that way, you can for instance first try to
authenticate the user via a certificate or an API key and fall back to a form login).
Mostly, you just need to make sure that this method returns true for a token that has been created by
createToken(). Your logic should probably look exactly like this example.
3. authenticateToken
If supportsToken() returns true, Symfony will now call authenticateToken(). One key part is
the $userProvider, which is an external class that helps you load information about the user. You'll
learn more about this next.
In this specific example, the following things happen in authenticateToken():
1. First, you use the $userProvider to somehow look up the $username that corresponds to the $apiKey;
2. Second, you use the $userProvider again to load or create a User object for the $username;
3. Finally, you create an authenticated token (i.e. a token with at least one role) that has the proper
roles and the User object attached to it.
The goal is ultimately to use the $apiKey to find or create a User object. How you do this (e.g. query a
database) and the exact class for your User object may vary. Those differences will be most obvious in
your user provider.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AppBundle/Security/ApiKeyUserProvider.php
namespace AppBundle\Security;
use
use
use
use
Symfony\Component\Security\Core\User\UserProviderInterface;
Symfony\Component\Security\Core\User\User;
Symfony\Component\Security\Core\User\UserInterface;
Symfony\Component\Security\Core\Exception\UnsupportedUserException;
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
return new User(
$username,
null,
// the roles for the user - you may choose to determine
// these dynamically somehow based on the user
array('ROLE_API')
);
}
public function refreshUser(UserInterface $user)
{
// this is used for storing authentication in the session
// but in this example, the token is sent in each request,
// so authentication can be stateless. Throwing this exception
// is proper to make things stateless
throw new UnsupportedUserException();
}
public function supportsClass($class)
{
return 'Symfony\Component\Security\Core\User\User' === $class;
}
}
1
2
3
4
# app/config/services.yml
services:
api_key_user_provider:
class: AppBundle\Security\ApiKeyUserProvider
Read the dedicated article to learn how to create a custom user provider.
The logic inside getUsernameForApiKey() is up to you. You may somehow transform the API key
(e.g. 37b51d) into a username (e.g. jondoe) by looking up some information in a "token" database
table.
The same is true for loadUserByUsername(). In this example, Symfony's core User3 class is simply
created. This makes sense if you don't need to store any extra information on your User object (e.g.
firstName). But if you do, you may instead have your own user class which you create and populate
here by querying a database. This would allow you to have custom data on the User object.
Finally, just make sure that supportsClass() returns true for User objects with the same class as
whatever user you return in loadUserByUsername().
If your authentication is stateless like in this example (i.e. you expect the user to send the API key
with every request and so you don't save the login to the session), then you can simply throw the
UnsupportedUserException exception in refreshUser().
If you do want to store authentication data in the session so that the key doesn't need to be sent on
every request, see Storing Authentication in the Session.
3. http://api.symfony.com/2.7/Symfony/Component/Security/Core/User/User.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Security/ApiKeyAuthenticator.php
namespace AppBundle\Security;
use
use
use
use
use
Symfony\Component\Security\Core\Authentication\SimplePreAuthenticatorInterface;
Symfony\Component\Security\Core\Exception\AuthenticationException;
Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
Symfony\Component\HttpFoundation\Response;
Symfony\Component\HttpFoundation\Request;
Configuration
Once you have your ApiKeyAuthenticator all setup, you need to register it as a service and use it in
your security configuration (e.g. security.yml). First, register it as a service.
Listing 106-5
1
2
3
4
5
6
7
# app/config/config.yml
services:
# ...
apikey_authenticator:
class: AppBundle\Security\ApiKeyAuthenticator
public: false
Now, activate it and your custom user provider (see How to Create a custom User Provider) in the
firewalls section of your security configuration using the simple_preauth and provider keys
respectively:
Listing 106-6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
pattern: ^/api
stateless: true
simple_preauth:
authenticator: apikey_authenticator
provider: api_key_user_provider
providers:
api_key_user_provider:
id: api_key_user_provider
4. http://api.symfony.com/2.7/Symfony/Component/Security/Http/Authentication/AuthenticationFailureHandlerInterface.html
1
2
3
4
5
6
# app/config/security.yml
security:
# ...
access_control:
- { path: ^/api, roles: ROLE_API }
That's it! Now, your ApiKeyAuthenticator should be called at the beginning of each request and
your authentication process will take place.
The stateless configuration parameter prevents Symfony from trying to store the authentication
information in the session, which isn't necessary since the client will send the apikey on each request. If
you do need to store authentication in the session, keep reading!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
pattern: ^/api
stateless: false
simple_preauth:
authenticator: apikey_authenticator
provider: api_key_user_provider
providers:
api_key_user_provider:
id: api_key_user_provider
Even though the token is being stored in the session, the credentials - in this case the API key (i.e.
$token->getCredentials()) - are not stored in the session for security reasons. To take advantage
of the session, update ApiKeyAuthenticator to see if the stored token has a valid User object that
can be used:
Listing 106-9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Security/ApiKeyAuthenticator.php
// ...
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface
{
// ...
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider,
$providerKey)
{
if (!$userProvider instanceof ApiKeyUserProvider) {
throw new \InvalidArgumentException(
sprintf(
'The user provider must be an instance of ApiKeyUserProvider (%s was given).',
get_class($userProvider)
)
);
}
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
$apiKey = $token->getCredentials();
$username = $userProvider->getUsernameForApiKey($apiKey);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Security/ApiKeyUserProvider.php
// ...
class ApiKeyUserProvider implements UserProviderInterface
{
// ...
public function refreshUser(UserInterface $user)
{
// $user is the User that you set in the token inside authenticateToken()
// after it has been deserialized from the session
// you might use $user to query the database for a fresh user
// $id = $user->getId();
// use $id to make a query
// if you are *not* reading from a database and are just creating
// a User object (like in this example), you can just return it
return $user;
}
}
You'll also want to make sure that your User object is being serialized correctly. If your User object
has private properties, PHP can't serialize those. In this case, you may get back a User object that has
a null value for each property. For an example, see How to Load Security Users from the Database
(the Entity Provider).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/AppBundle/Security/ApiKeyAuthenticator.php
// ...
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpFoundation\Request;
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface
{
protected $httpUtils;
public function __construct(HttpUtils $httpUtils)
{
$this->httpUtils = $httpUtils;
}
public function createToken(Request $request, $providerKey)
{
// set the only URL where we should look for auth information
// and only return the token if we're at that URL
$targetUrl = '/login/check';
if (!$this->httpUtils->checkRequestPath($request, $targetUrl)) {
return;
}
// ...
}
}
This uses the handy HttpUtils5 class to check if the current URL matches the URL you're looking for.
In this case, the URL (/login/check) has been hardcoded in the class, but you could also inject it as
the second constructor argument.
Next, just update your service configuration to inject the security.http_utils service:
Listing 106-12 1
2
3
4
5
6
7
8
# app/config/config.yml
services:
# ...
apikey_authenticator:
class:
AppBundle\Security\ApiKeyAuthenticator
arguments: ["@security.http_utils"]
public:
false
5. http://api.symfony.com/2.7/Symfony/Component/Security/Http/HttpUtils.html
Chapter 107
Creating a custom authentication system is hard, and this entry will walk you through that process.
But depending on your needs, you may be able to solve your problem in a simpler, or via a
community bundle:
How to Create a Custom Form Password Authenticator
How to Authenticate Users with API Keys
To authenticate via OAuth using a third-party service such as Google, Facebook or Twitter, try
using the HWIOAuthBundle1 community bundle.
If you have read the chapter on Security, you understand the distinction Symfony makes between
authentication and authorization in the implementation of security. This chapter discusses the core
classes involved in the authentication process, and how to implement a custom authentication provider.
Because authentication and authorization are separate concepts, this extension will be user-provider
agnostic, and will function with your application's user providers, may they be based in memory, a
database, or wherever else you choose to store them.
Meet WSSE
The following chapter demonstrates how to create a custom authentication provider for WSSE
authentication. The security protocol for WSSE provides several security benefits:
1. Username / Password encryption
2. Safe guarding against replay attacks
3. No web server configuration required
WSSE is very useful for the securing of web services, may they be SOAP or REST.
1. https://github.com/hwi/HWIOAuthBundle
There is plenty of great documentation on WSSE2, but this article will focus not on the security protocol,
but rather the manner in which a custom protocol can be added to your Symfony application. The basis
of WSSE is that a request header is checked for encrypted credentials, verified using a timestamp and
nonce3, and authenticated for the requested user using a password digest.
WSSE also supports application key validation, which is useful for web services, but is outside the
scope of this chapter.
The Token
The role of the token in the Symfony security context is an important one. A token represents the user
authentication data present in the request. Once a request is authenticated, the token retains the user's
data, and delivers this data across the security context. First, you'll create your token class. This will allow
the passing of all relevant information to your authentication provider.
Listing 107-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/AppBundle/Security/Authentication/Token/WsseUserToken.php
namespace AppBundle\Security\Authentication\Token;
use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
class WsseUserToken extends AbstractToken
{
public $created;
public $digest;
public $nonce;
public function __construct(array $roles = array())
{
parent::__construct($roles);
The WsseUserToken class extends the Security component's AbstractToken4 class, which
provides basic token functionality. Implement the TokenInterface5 on any class to use as a token.
The Listener
Next, you need a listener to listen on the firewall. The listener is responsible for fielding requests
to the firewall and calling the authentication provider. A listener must be an instance of
2. http://www.xml.com/pub/a/2003/12/17/dive.html
3. https://en.wikipedia.org/wiki/Cryptographic_nonce
4. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.html
5. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.html
ListenerInterface6. A security listener should handle the GetResponseEvent7 event, and set an
authenticated token in the token storage if successful.
Listing 107-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// src/AppBundle/Security/Firewall/WsseListener.php
namespace AppBundle\Security\Firewall;
use
use
use
use
use
use
use
Symfony\Component\HttpFoundation\Response;
Symfony\Component\HttpKernel\Event\GetResponseEvent;
Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
Symfony\Component\Security\Core\Exception\AuthenticationException;
Symfony\Component\Security\Http\Firewall\ListenerInterface;
AppBundle\Security\Authentication\Token\WsseUserToken;
= $matches[2];
= $matches[3];
= $matches[4];
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
// ... you might log something here
//
//
//
//
//
//
//
To deny the authentication clear the token. This will redirect to the login page.
Make sure to only clear your token, not those of other authentication listeners.
$token = $this->tokenStorage->getToken();
if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) {
$this->tokenStorage->setToken(null);
}
return;
6. http://api.symfony.com/2.7/Symfony/Component/Security/Http/Firewall/ListenerInterface.html
7. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/Event/GetResponseEvent.html
This listener checks the request for the expected X-WSSE header, matches the value returned for the
expected WSSE information, creates a token using that information, and passes the token on to the
authentication manager. If the proper information is not provided, or the authentication manager throws
an AuthenticationException8, a 403 Response is returned.
A class not used above, the AbstractAuthenticationListener9 class, is a very useful base
class which provides commonly needed functionality for security extensions. This includes
maintaining the token in the session, providing success / failure handlers, login form URLs, and
more. As WSSE does not require maintaining authentication sessions or login forms, it won't be used
for this example.
Returning prematurely from the listener is relevant only if you want to chain authentication
providers (for example to allow anonymous users). If you want to forbid access to anonymous users
and have a nice 403 error, you should set the status code of the response before returning.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/AppBundle/Security/Authentication/Provider/WsseProvider.php
namespace AppBundle\Security\Authentication\Provider;
use
use
use
use
use
use
use
Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
Symfony\Component\Security\Core\User\UserProviderInterface;
Symfony\Component\Security\Core\Exception\AuthenticationException;
Symfony\Component\Security\Core\Exception\NonceExpiredException;
Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
AppBundle\Security\Authentication\Token\WsseUserToken;
Symfony\Component\Security\Core\Util\StringUtils;
8. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Exception/AuthenticationException.html
9. http://api.symfony.com/2.7/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.html
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* This function is specific to Wsse authentication and is only used to help this example
*
* For more information specific to the logic here, see
* https://github.com/symfony/symfony-docs/pull/3134#issuecomment-27699129
*/
protected function validateDigest($digest, $nonce, $created, $secret)
{
// Check created time is not in the future
if (strtotime($created) > time()) {
return false;
}
// Expire timestamp after 5 minutes
if (time() - strtotime($created) > 300) {
return false;
}
// Validate that the nonce is *not* used in the last 5 minutes
// if it has, this could be a replay attack
if (
file_exists($this->cacheDir.'/'.md5($nonce))
&& file_get_contents($this->cacheDir.'/'.md5($nonce)) + 300 > time()
) {
throw new NonceExpiredException('Previously used nonce detected');
}
// If cache directory does not exist we create it
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0777, true);
}
file_put_contents($this->cacheDir.'/'.md5($nonce), time());
// Validate Secret
$expected = base64_encode(sha1(base64_decode($nonce).$created.$secret, true));
return StringUtils::equals($expected, $digest);
}
public function supports(TokenInterface $token)
{
return $token instanceof WsseUserToken;
}
}
The Factory
You have created a custom token, custom listener, and custom provider. Now you need to tie them all
together. How do you make a unique provider available for every firewall? The answer is by using a
10. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/Provider/AuthenticationProviderInterface.html
11. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Util/StringUtils.html#method_equals
12. https://en.wikipedia.org/wiki/Timing_attack
factory. A factory is where you hook into the Security component, telling it the name of your provider
and any configuration options available for it. First, you must create a class which implements
SecurityFactoryInterface13.
Listing 107-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// src/AppBundle/DependencyInjection/Security/Factory/WsseFactory.php
namespace AppBundle\DependencyInjection\Security\Factory;
use
use
use
use
use
Symfony\Component\DependencyInjection\ContainerBuilder;
Symfony\Component\DependencyInjection\Reference;
Symfony\Component\DependencyInjection\DefinitionDecorator;
Symfony\Component\Config\Definition\Builder\NodeDefinition;
Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
Method which adds the listener and authentication provider to the DI container for the appropriate
security context.
getPosition
Returns when the provider should be called. This can be one of pre_auth, form, http or remember_me.
getKey
Method which defines the configuration key used to reference the provider in the firewall
configuration.
addConfiguration
Method which is used to define the configuration options underneath the configuration key in your
security configuration. Setting configuration options are explained later in this chapter.
13. http://api.symfony.com/2.7/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.html
14. http://api.symfony.com/2.7/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.html
A class not used in this example, AbstractFactory15, is a very useful base class which provides
commonly needed functionality for security factories. It may be useful when defining an
authentication provider of a different type.
Now that you have created a factory class, the wsse key can be used as a firewall in your security
configuration.
You may be wondering "why do you need a special factory class to add listeners and providers to
the dependency injection container?". This is a very good question. The reason is you can use your
firewall multiple times, to secure multiple parts of your application. Because of this, each time your
firewall is used, a new service is created in the DI container. The factory is what creates these new
services.
Configuration
It's time to see your authentication provider in action. You will need to do a few things in order to
make this work. The first thing is to add the services above to the DI container. Your factory class above
makes reference to service ids that do not exist yet: wsse.security.authentication.provider
and wsse.security.authentication.listener. It's time to define those services.
Listing 107-5
1
2
3
4
5
6
7
8
9
10
11
12
13
# app/config/services.yml
services:
wsse.security.authentication.provider:
class: AppBundle\Security\Authentication\Provider\WsseProvider
arguments:
- '' # User Provider
- '%kernel.cache_dir%/security/nonces'
public: false
wsse.security.authentication.listener:
class: AppBundle\Security\Firewall\WsseListener
arguments: ['@security.token_storage', '@security.authentication.manager']
public: false
Now that your services are defined, tell your security context about your factory in your bundle class:
Listing 107-6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/AppBundle.php
namespace AppBundle;
use AppBundle\DependencyInjection\Security\Factory\WsseFactory;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$extension = $container->getExtension('security');
$extension->addSecurityListenerFactory(new WsseFactory());
}
}
You are finished! You can now define parts of your app as under WSSE protection.
Listing 107-7
15. http://api.symfony.com/2.7/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.html
1
2
3
4
5
6
7
8
9
# app/config/security.yml
security:
# ...
firewalls:
wsse_secured:
pattern: ^/api/
stateless: true
wsse:
true
Congratulations! You have written your very own custom security authentication provider!
A little Extra
How about making your WSSE authentication provider a bit more exciting? The possibilities are endless.
Why don't you start by adding some sparkle to that shine?
Configuration
You can add custom options under the wsse key in your security configuration. For instance, the time
allowed before expiring the Created header item, by default, is 5 minutes. Make this configurable, so
different firewalls can have different timeout lengths.
You will first need to edit WsseFactory and define the new option in the addConfiguration
method.
Listing 107-8
1
2
3
4
5
6
7
8
9
10
11
12
Now, in the create method of the factory, the $config argument will contain a lifetime key,
set to 5 minutes (300 seconds) unless otherwise set in the configuration. Pass this argument to your
authentication provider in order to put it to use.
Listing 107-9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ...
}
The lifetime of each WSSE request is now configurable, and can be set to any desirable value per firewall.
Listing 107-10 1
2
3
4
5
6
7
8
9
# app/config/security.yml
security:
# ...
firewalls:
wsse_secured:
pattern:
^/api/
stateless: true
wsse:
{ lifetime: 30 }
The rest is up to you! Any relevant configuration items can be defined in the factory and consumed or
passed to the other classes in the container.
Chapter 108
1
2
3
4
5
6
7
8
9
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
pattern: ^/
x509:
provider: your_user_provider
By default, the firewall provides the SSL_CLIENT_S_DN_Email variable to the user provider, and sets
the SSL_CLIENT_S_DN as credentials in the PreAuthenticatedToken1. You can override these by
setting the user and the credentials keys in the x509 firewall configuration respectively.
1. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.html
An authentication provider will only inform the user provider of the username that made the request.
You will need to create (or use) a "user provider" that is referenced by the provider configuration
parameter (your_user_provider in the configuration example). This provider will turn the
username into a User object of your choice. For more information on creating or configuring a user
provider, see:
How to Create a custom User Provider
How to Load Security Users from the Database (the Entity Provider)
1
2
3
4
5
6
7
# app/config/security.yml
security:
firewalls:
secured_area:
pattern: ^/
remote_user:
provider: your_user_provider
The firewall will then provide the REMOTE_USER environment variable to your user provider. You can
change the variable name used by setting the user key in the remote_user firewall configuration.
Just like for X509 authentication, you will need to configure a "user provider". See the previous note
for more information.
Chapter 109
1
2
3
4
# app/config/services.yml
parameters:
# ...
security.exception_listener.class: AppBundle\Security\Firewall\ExceptionListener
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Security/Firewall/ExceptionListener.php
namespace AppBundle\Security\Firewall;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Firewall\ExceptionListener as BaseExceptionListener;
class ExceptionListener extends BaseExceptionListener
{
protected function setTargetPath(Request $request)
{
// Do not save target path for XHR requests
// You can add any more logic here you want
Chapter 109: How to Change the default Target Path Behavior | 388
13
14
15
16
17
18
19
20
Chapter 109: How to Change the default Target Path Behavior | 389
Chapter 110
1
2
3
4
5
6
7
8
9
10
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
# ...
form_login:
# ...
csrf_provider: security.csrf.token_manager
The Security component can be configured further, but this is all information it needs to be able to use
CSRF in the login form.
1. https://en.wikipedia.org/wiki/Cross-site_request_forgery
2. https://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests
1
2
3
4
5
6
7
8
9
10
11
12
{# src/AppBundle/Resources/views/Security/login.html.twig #}
{# ... #}
<form action="{{ path('login') }}" method="post">
{# ... the login fields #}
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
<button type="submit">login</button>
</form>
After this, you have protected your login form against CSRF attacks.
You can change the name of the field by setting csrf_parameter and change the token ID by
setting intention in your configuration:
Listing 110-3
1
2
3
4
5
6
7
8
9
10
11
# app/config/security.yml
security:
# ...
firewalls:
secured_area:
# ...
form_login:
# ...
csrf_parameter: _csrf_security_token
intention: a_private_string
Chapter 111
# app/config/security.yml
security:
# ...
encoders:
Symfony\Component\Security\Core\User\User: sha512
1
2
3
4
5
Another option is to use a "named" encoder and then select which encoder you want to use dynamically.
In the previous example, you've set the sha512 algorithm for Acme\UserBundle\Entity\User. This
may be secure enough for a regular user, but what if you want your admins to have a stronger algorithm,
for example bcrypt. This can be done with named encoders:
Listing 111-2
# app/config/security.yml
security:
# ...
encoders:
harsh:
algorithm: bcrypt
cost: 15
1
2
3
4
5
6
7
This creates an encoder named harsh. In order for a User instance to use it, the class must implement
EncoderAwareInterface1. The interface requires one method - getEncoderName - which should
return the name of the encoder to use:
Listing 111-3
1
2
3
4
5
6
// src/Acme/UserBundle/Entity/User.php
namespace Acme\UserBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Encoder\EncoderAwareInterface;
1. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Encoder/EncoderAwareInterface.html
Chapter 111: How to Choose the Password Encoder Algorithm Dynamically | 392
7
8
9
10
11
12
13
14
15
16
17
Chapter 111: How to Choose the Password Encoder Algorithm Dynamically | 393
Chapter 112
1
2
3
4
5
6
7
8
9
10
11
12
# app/config/security.yml
security:
providers:
chain_provider:
chain:
providers: [in_memory, user_db]
in_memory:
memory:
users:
foo: { password: test }
user_db:
entity: { class: AppBundle\Entity\User, property: username }
Now, all authentication mechanisms will use the chain_provider, since it's the first specified. The
chain_provider will, in turn, try to load the user from both the in_memory and user_db providers.
You can also configure the firewall or individual authentication mechanisms to use a specific provider.
Again, unless a provider is specified explicitly, the first provider is always used:
Listing 112-2
1
2
3
4
5
6
7
8
9
10
11
# app/config/security.yml
security:
firewalls:
secured_area:
# ...
pattern: ^/
provider: user_db
http_basic:
realm: 'Secured Demo Area'
provider: in_memory
form_login: ~
In this example, if a user tries to log in via HTTP authentication, the authentication system will use the
in_memory user provider. But if the user tries to log in via the form login, the user_db provider will be
used (since it's the default for the firewall as a whole).
For more information about user provider and firewall configuration, see the SecurityBundle
Configuration ("security").
Chapter 113
Restricting by Pattern
This is the default restriction and restricts a firewall to only be initialized if the request URL matches the
configured pattern.
Listing 113-1
1
2
3
4
5
6
7
8
# app/config/security.yml
# ...
security:
firewalls:
secured_area:
pattern: ^/admin
# ...
The pattern is a regular expression. In this example, the firewall will only be activated if the URL starts
(due to the ^ regex character) with /admin. If the URL does not match this pattern, the firewall will not
be activated and subsequent firewalls will have the opportunity to be matched for this request.
Restricting by Host
If matching against the pattern only is not enough, the request can also be matched against host.
When the configuration option host is set, the firewall will be restricted to only initialize if the host from
the request matches against the configuration.
Listing 113-2
1
2
3
4
5
6
7
8
# app/config/security.yml
# ...
security:
firewalls:
secured_area:
host: ^admin\.example\.com$
# ...
The host (like the pattern) is a regular expression. In this example, the firewall will only be activated
if the host is equal exactly (due to the ^ and $ regex characters) to the hostname admin.example.com.
If the hostname does not match this pattern, the firewall will not be activated and subsequent firewalls
will have the opportunity to be matched for this request.
1
2
3
4
5
6
7
8
# app/config/security.yml
# ...
security:
firewalls:
secured_area:
methods: [GET, POST]
# ...
In this example, the firewall will only be activated if the HTTP method of the request is either GET or
POST. If the method is not in the array of the allowed methods, the firewall will not be activated and
subsequent firewalls will again have the opportunity to be matched for this request.
Chapter 114
Chapter 115
1
2
3
1. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authorization/Voter/VoterInterface.html
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authorization/Voter/AbstractVoter.html
4
5
6
In this example, the voter will check if the user has access to a specific object according to your
custom conditions (e.g. they must be the owner of the object). If the condition fails, you'll return
VoterInterface::ACCESS_DENIED,
otherwise
you'll
return
VoterInterface::ACCESS_GRANTED. In case the responsibility for this decision does not belong to
this voter, it will return VoterInterface::ACCESS_ABSTAIN.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// src/AppBundle/Security/Authorization/Voter/PostVoter.php
namespace AppBundle\Security\Authorization\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;
class PostVoter extends AbstractVoter
{
const VIEW = 'view';
const EDIT = 'edit';
protected function getSupportedAttributes()
{
return array(self::VIEW, self::EDIT);
}
protected function getSupportedClasses()
{
return array('AppBundle\Entity\Post');
}
protected function isGranted($attribute, $post, $user = null)
{
// make sure there is a user object (i.e. that the user is logged in)
if (!$user instanceof UserInterface) {
return false;
}
51
52
53
54
55
56
57
break;
}
return false;
}
}
That's it! The voter is done. The next step is to inject the voter into the security layer.
To recap, here's what's expected from the three abstract methods:
getSupportedClasses()3
It tells Symfony that your voter should be called whenever an object of one of the given classes
is passed to isGranted(). For example, if you return array('AppBundle\Model\Product'), Symfony will call
your voter when a Product object is passed to isGranted().
getSupportedAttributes()4
It tells Symfony that your voter should be called whenever one of these strings is passed as the first
argument to isGranted(). For example, if you return array('CREATE', 'READ'), then Symfony will call your
voter when one of these is passed to isGranted().
isGranted()5
It implements the business logic that verifies whether or not a given user is allowed access to a given
attribute (e.g. CREATE or READ) on a given object. This method must return a boolean.
Currently, to use the AbstractVoter base class, you must be creating a voter where an object is
always passed to isGranted().
# app/config/services.yml
services:
security.access.post_voter:
class:
AppBundle\Security\Authorization\Voter\PostVoter
public:
false
tags:
- { name: security.voter }
1
2
3
4
5
6
7
1
2
// src/AppBundle/Controller/PostController.php
namespace AppBundle\Controller;
3. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authorization/Voter/AbstractVoter.html#method_getSupportedClasses
4. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authorization/Voter/AbstractVoter.html#method_getSupportedAttributes
5. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Authorization/Voter/AbstractVoter.html#method_isGranted
6. http://api.symfony.com/2.7/Symfony/Bundle/FrameworkBundle/Controller/Controller.html#method_denyAccessUnlessGranted()
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class PostController extends Controller
{
public function showAction($id)
{
// get a Post instance
$post = ...;
// keep in mind that this will call all registered security voters
$this->denyAccessUnlessGranted('view', $post, 'Unauthorized access!');
return new Response('<h1>'.$post->getName().'</h1>');
}
}
New in version 2.6: The denyAccessUnlessGranted() method was introduced in Symfony 2.6. Prior
to Symfony 2.6, you had to call the isGranted() method of the security.context service and
throw the exception yourself.
It's that easy!
This grants access if there are more voters granting access than denying;
unanimous
1
2
3
4
# app/config/security.yml
security:
access_decision_manager:
strategy: unanimous
Chapter 116
Alternatives to ACLs
Using ACL's isn't trivial, and for simpler use cases, it may be overkill. If your permission logic
could be described by just writing some code (e.g. to check if a Blog is owned by the current
User), then consider using voters. A voter is passed the object being voted on, which you can use to
make complex decisions and effectively implement your own ACL. Enforcing authorization (e.g. the
isGranted part) will look similar to what you see in this entry, but your voter class will handle the
logic behind the scenes, instead of the ACL system.
Imagine you are designing a blog system where your users can comment on your posts. Now, you want a
user to be able to edit their own comments, but not those of other users; besides, you yourself want to be
able to edit all comments. In this scenario, Comment would be the domain object that you want to restrict
access to. You could take several approaches to accomplish this using Symfony, two basic approaches are
(non-exhaustive):
Enforce security in your business methods: Basically, that means keeping a reference inside each
Comment to all users who have access, and then compare these users to the provided Token.
Enforce security with roles: In this approach, you would add a role for each Comment object, i.e.
ROLE_COMMENT_1, ROLE_COMMENT_2, etc.
Both approaches are perfectly valid. However, they couple your authorization logic to your business code
which makes it less reusable elsewhere, and also increases the difficulty of unit testing. Besides, you could
run into performance issues if many users would have access to a single domain object.
Fortunately, there is a better way, which you will find out about now.
Bootstrapping
Now, before you can finally get into action, you need to do some bootstrapping. First, you need to
configure the connection the ACL system is supposed to use:
Listing 116-1
1
2
3
4
5
6
# app/config/security.yml
security:
# ...
acl:
connection: default
The ACL system requires a connection from either Doctrine DBAL (usable by default) or Doctrine
MongoDB (usable with MongoDBAclBundle1). However, that does not mean that you have to use
Doctrine ORM or ODM for mapping your domain objects. You can use whatever mapper you like
for your objects, be it Doctrine ORM, MongoDB ODM, Propel, raw SQL, etc. The choice is yours.
After the connection is configured, you have to import the database structure. Fortunately, there is a task
for this. Simply run the following command:
Listing 116-2
Getting Started
Coming back to the small example from the beginning, you can now implement ACL for it.
Once the ACL is created, you can grant access to objects by creating an Access Control Entry (ACE) to
solidify the relationship between the entity and your user.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/AppBundle/Controller/BlogController.php
namespace AppBundle\Controller;
use
use
use
use
use
Symfony\Bundle\FrameworkBundle\Controller\Controller;
Symfony\Component\Security\Core\Exception\AccessDeniedException;
Symfony\Component\Security\Acl\Domain\ObjectIdentity;
Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
Symfony\Component\Security\Acl\Permission\MaskBuilder;
1. https://github.com/IamPersistent/MongoDBAclBundle
27
28
29
30
31
32
33
34
35
36
37
38
39
40
$objectIdentity = ObjectIdentity::fromDomainObject($comment);
$acl = $aclProvider->createAcl($objectIdentity);
There are a couple of important implementation decisions in this code snippet. For now, I only want to
highlight two:
First, you may have noticed that ->createAcl() does not accept domain objects directly, but only
implementations of the ObjectIdentityInterface. This additional step of indirection allows you to
work with ACLs even when you have no actual domain object instance at hand. This will be extremely
helpful if you want to check permissions for a large number of objects without actually hydrating these
objects.
The other interesting part is the ->insertObjectAce() call. In the example, you are granting the user
who is currently logged in owner access to the Comment. The MaskBuilder::MASK_OWNER is a predefined integer bitmask; don't worry the mask builder will abstract away most of the technical details,
but using this technique you can store many different permissions in one database row which gives a
considerable boost in performance.
The order in which ACEs are checked is significant. As a general rule, you should place more specific
entries at the beginning.
Checking Access
Listing 116-4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AppBundle/Controller/BlogController.php
// ...
class BlogController
{
// ...
public function editCommentAction(Comment $comment)
{
$authorizationChecker = $this->get('security.authorization_checker');
In this example, you check whether the user has the EDIT permission. Internally, Symfony maps the
permission to several integer bitmasks, and checks whether the user has any of them.
You can define up to 32 base permissions (depending on your OS PHP might vary between 30 to
32). In addition, you can also define cumulative permissions.
Cumulative Permissions
In the first example above, you only granted the user the OWNER base permission. While this effectively
also allows the user to perform any operation such as view, edit, etc. on the domain object, there are
cases where you may want to grant these permissions explicitly.
The MaskBuilder can be used for creating bit masks easily by combining several base permissions:
Listing 116-5
1
2
3
4
5
6
7
8
This integer bitmask can then be used to grant a user the base permissions you added above:
Listing 116-6
1
2
The user is now allowed to view, edit, delete, and un-delete objects.
Chapter 117
Design Concepts
Symfony's object instance security capabilities are based on the concept of an Access Control List. Every
domain object instance has its own ACL. The ACL instance holds a detailed list of Access Control
Entries (ACEs) which are used to make access decisions. Symfony's ACL system focuses on two main
objectives:
providing a way to efficiently retrieve a large amount of ACLs/ACEs for your domain objects, and
to modify them;
providing a way to easily make decisions of whether a person is allowed to perform an action on a
domain object or not.
As indicated by the first point, one of the main capabilities of Symfony's ACL system is a highperformance way of retrieving ACLs/ACEs. This is extremely important since each ACL might have
several ACEs, and inherit from another ACL in a tree-like fashion. Therefore, no ORM is leveraged,
instead the default implementation interacts with your connection directly using Doctrine's DBAL.
Object Identities
The ACL system is completely decoupled from your domain objects. They don't even have to be stored
in the same database, or on the same server. In order to achieve this decoupling, in the ACL system your
objects are represented through object identity objects. Every time you want to retrieve the ACL for a
domain object, the ACL system will first create an object identity from your domain object, and then pass
this object identity to the ACL provider for further processing.
Security Identities
This is analog to the object identity, but represents a user, or a role in your application. Each role, or user
has its own security identity.
For users, the security identity is based on the username. This means that, if for any reason,
a user's username was to change, you must ensure its security identity is updated too. The
MutableAclProvider::updateUserSecurityIdentity()1 method is there to handle the
update.
Pre-Authorization Decisions
For pre-authorization decisions, that is decisions made before any secure method (or secure action) is
invoked, the proven AccessDecisionManager service is used. The AccessDecisionManager is also used
for reaching authorization decisions based on roles. Just like roles, the ACL system adds several new
attributes which may be used to check for different permissions.
1. http://api.symfony.com/2.7/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.html#method_updateUserSecurityIdentity
2. http://api.symfony.com/2.7/Symfony/Component/Security/Acl/Domain/RoleSecurityIdentity.html
3. http://api.symfony.com/2.7/Symfony/Component/Security/Acl/Domain/UserSecurityIdentity.html
Intended Meaning
Integer Bitmasks
VIEW
EDIT
CREATE
DELETE
UNDELETE
UNDELETE, OPERATOR,
MASTER, or OWNER
OPERATOR
MASTER
MASTER, or OWNER
OWNER
OWNER
Extensibility
The above permission map is by no means static, and theoretically could be completely replaced at will.
However, it should cover most problems you encounter, and for interoperability with other bundles, you
are encouraged to stick to the meaning envisaged for them.
Due to current limitations of the PHP language, there are no post-authorization capabilities build into the
core Security component. However, there is an experimental JMSSecurityExtraBundle4 which adds these
capabilities. See its documentation for further information on how this is accomplished.
4. https://github.com/schmittjoh/JMSSecurityExtraBundle
5. http://api.symfony.com/2.7/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.html
Chapter 118
1
2
3
4
5
6
# app/config/security.yml
security:
# ...
access_control:
- { path: ^/secure, roles: ROLE_ADMIN, requires_channel: https }
The login form itself needs to allow anonymous access, otherwise users will be unable to authenticate.
To force it to use HTTPS you can still use access_control rules by using the
IS_AUTHENTICATED_ANONYMOUSLY role:
Listing 118-2
1
2
3
4
5
6
# app/config/security.yml
security:
# ...
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
It is also possible to specify using HTTPS in the routing configuration, see How to Force Routes to always
Use HTTPS or HTTP for more details.
Chapter 118: How to Force HTTPS or HTTP for different URLs | 411
Chapter 119
1
2
3
4
5
6
7
8
9
// ...
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
public function helloAction($name)
{
$this->denyAccessUnlessGranted('ROLE_ADMIN');
// ...
}
You can also secure any service by injecting the security.authorization_checker service into it.
For a general introduction to injecting dependencies into services see the Service Container chapter of the
book. For example, suppose you have a NewsletterManager class that sends out emails and you want
to restrict its use to only users who have some ROLE_NEWSLETTER_ADMIN role. Before you add security,
the class looks something like this:
Listing 119-2
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Newsletter/NewsletterManager.php
namespace AppBundle\Newsletter;
class NewsletterManager
{
public function sendNewsletter()
{
// ... where you actually do the work
}
// ...
}
Your goal is to check the user's role when the sendNewsletter() method is called. The first step
towards this is to inject the security.authorization_checker service into the object. Since it
PDF brought to you by
generated on July 28, 2016
Chapter 119: How to Secure any Service or Method in your Application | 412
won't make sense not to perform the security check, this is an ideal candidate for constructor injection,
which guarantees that the authorization checker object will be available inside the
NewsletterManager class:
Listing 119-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/AppBundle/Newsletter/NewsletterManager.php
// ...
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class NewsletterManager
{
protected $authorizationChecker;
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
// ...
}
1
2
3
4
5
# app/config/services.yml
services:
newsletter_manager:
class:
AppBundle\Newsletter\NewsletterManager
arguments: ['@security.authorization_checker']
The injected service can then be used to perform the security check when the sendNewsletter()
method is called:
Listing 119-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace AppBundle\Newsletter;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
// ...
class NewsletterManager
{
protected $authorizationChecker;
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
public function sendNewsletter()
{
if (false === $this->authorizationChecker->isGranted('ROLE_NEWSLETTER_ADMIN')) {
throw new AccessDeniedException();
}
// ...
}
// ...
}
If the current user does not have the ROLE_NEWSLETTER_ADMIN, they will be prompted to log in.
Chapter 119: How to Secure any Service or Method in your Application | 413
# app/config/services.yml
services:
newsletter_manager:
class: AppBundle\Newsletter\NewsletterManager
tags:
- { name: security.secure_service }
1
2
3
4
5
6
You can then achieve the same results as above using an annotation:
Listing 119-7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace AppBundle\Newsletter;
use JMS\SecurityExtraBundle\Annotation\Secure;
// ...
class NewsletterManager
{
/**
* @Secure(roles="ROLE_NEWSLETTER_ADMIN")
*/
public function sendNewsletter()
{
// ...
}
// ...
}
The annotations work because a proxy class is created for your class which performs the security
checks. This means that, whilst you can use annotations on public and protected methods, you
cannot use them with private methods or methods marked final.
The JMSSecurityExtraBundle also allows you to secure the parameters and return values of methods. For
more information, see the JMSSecurityExtraBundle2 documentation.
1
2
3
4
# app/config/config.yml
jms_security_extra:
# ...
secure_all_services: true
The disadvantage of this method is that, if activated, the initial page load may be very slow
depending on how many services you have defined.
1. https://github.com/schmittjoh/JMSSecurityExtraBundle
2. https://github.com/schmittjoh/JMSSecurityExtraBundle
Chapter 119: How to Secure any Service or Method in your Application | 414
Chapter 120
1. Matching Options
Symfony creates an instance of RequestMatcher1 for each access_control entry, which determines
whether or not a given access control should be used on this request. The following access_control
options are used for matching:
path
ip
or ips
host
methods
1
2
3
4
5
6
7
8
# app/config/security.yml
security:
# ...
access_control:
- { path: ^/admin,
- { path: ^/admin,
- { path: ^/admin,
- { path: ^/admin,
roles:
roles:
roles:
roles:
For each incoming request, Symfony will decide which access_control to use based on the URI,
the client's IP address, the incoming host name, and the request method. Remember, the first rule that
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/RequestMatcher.html
matches is used, and if ip, host or method are not specified for an entry, that access_control will
match any ip, host or method:
URI
IP
/admin/
HOST
METHOD
access_control
Why?
rule #1
(ROLE_USER_IP)
rule #1
(ROLE_USER_IP)
rule #2
(ROLE_USER_HOST)
rule #2
(ROLE_USER_HOST)
rule #3
(ROLE_USER_METHOD)
rule #4
(ROLE_USER)
matches no
entries
user
/admin/
user
/admin/
user
/admin/
user
/admin/
user
/admin/
user
/foo
2. Access Enforcement
Once Symfony has decided which access_control entry matches (if any), it then enforces access
restrictions based on the roles, allow_if and requires_channel options:
If the user does not have the given role(s), then access is denied (internally, an
is thrown);
allow_if If the expression returns false, then access is denied;
requires_channel If the incoming request's channel (e.g. http) does not match this value (e.g. https), the
user will be redirected (e.g. redirected from http to https, or vice versa).
role
AccessDeniedException2
If access is denied, the system will try to authenticate the user if not already (e.g. redirect the user to
the login page). If the user is already logged in, the 403 "access denied" error page will be shown. See
How to Customize Error Pages for more information.
2. http://api.symfony.com/2.7/Symfony/Component/Security/Core/Exception/AccessDeniedException.html
Matching access_control By IP
Certain situations may arise when you need to have an access_control entry that only matches
requests coming from some IP address or range. For example, this could be used to deny access to a URL
pattern to all requests except those from a trusted, internal server.
As you'll read in the explanation below the example, the ips option does not restrict to a specific IP
address. Instead, using the ips key means that the access_control entry will only match this IP
address, and users accessing it from a different IP address will continue down the access_control
list.
Here is an example of how you configure some example /internal* URL pattern so that it is only
accessible by requests from the local server itself:
Listing 120-2
1
2
3
4
5
6
7
# app/config/security.yml
security:
# ...
access_control:
#
- { path: ^/internal, roles: IS_AUTHENTICATED_ANONYMOUSLY, ips: [127.0.0.1, ::1] }
- { path: ^/internal, roles: ROLE_NO_ACCESS }
Here is how it works when the path is /internal/something coming from the external IP address
10.0.0.1:
The first access control rule is ignored as the path matches but the IP address does not match either
of the IPs listed;
The second access control rule is enabled (the only restriction being the path) and so it matches.
If you make sure that no users ever have ROLE_NO_ACCESS, then access is denied (ROLE_NO_ACCESS can be
anything that does not match an existing role, it just serves as a trick to always deny access).
But if the same request comes from 127.0.0.1 or ::1 (the IPv6 loopback address):
Now, the first access control rule is enabled as both the path and the ip match: access is allowed as
the user always has the IS_AUTHENTICATED_ANONYMOUSLY role.
The second access rule is not examined as the first rule matched.
Securing by an Expression
Once an access_control entry is matched, you can deny access via the roles key or use more
complex logic with an expression in the allow_if key:
Listing 120-3
1
2
3
4
5
6
7
# app/config/security.yml
security:
# ...
access_control:
path: ^/_internal/secure
allow_if: "'127.0.0.1' == request.getClientIp() or has_role('ROLE_ADMIN')"
In this case, when the user tries to access any URL starting with /_internal/secure, they will only
be granted access if the IP address is 127.0.0.1 or if the user has the ROLE_ADMIN role.
Inside the expression, you have access to a number of different variables and functions including
request, which is the Symfony Request3 object (see Request).
3. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html
For a list of the other functions and variables, see functions and variables.
1
2
3
4
5
# app/config/security.yml
security:
# ...
access_control:
- { path: ^/cart/checkout, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
Chapter 121
# app/config/config.yml
framework:
# ...
serializer:
enabled: true
1
2
3
4
5
1
2
3
4
5
6
7
8
9
// src/AppBundle/Controller/DefaultController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
10
11
12
13
14
$serializer = $this->get('serializer');
// ...
}
}
1
2
3
4
5
6
# app/config/services.yml
services:
get_set_method_normalizer:
class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
tags:
- { name: serializer.normalizer }
1
2
3
4
5
# app/config/config.yml
framework:
# ...
serializer:
enable_annotations: true
Next, add the @Groups annotations to your class and choose which groups to use when serializing:
Listing 121-5
1
2
3
4
5
$serializer = $this->get('serializer');
$json = $serializer->serialize(
$someObject,
'json', array('groups' => array('group1'))
);
In addition to the @Groups annotation, the Serializer component also supports Yaml or XML files. These
files are automatically loaded when being stored in one of the following locations:
The serialization.yml or serialization.xml file in the Resources/config/ directory of a bundle;
All *.yml and *.xml files in the Resources/config/serialization/ directory of a bundle.
1. http://api.symfony.com/2.7/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.html
2. http://api.symfony.com/2.7/Symfony/Component/Serializer/Encoder/JsonEncoder.html
3. http://api.symfony.com/2.7/Symfony/Component/Serializer/Encoder/XmlEncoder.html
4. http://api.symfony.com/2.7/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.html
1
2
3
4
5
# app/config/config_prod.yml
framework:
# ...
serializer:
cache: serializer.mapping.cache.apc
5. https://github.com/krakjoe/apcu
6. https://github.com/api-platform/core
7. http://json-ld.org
8. http://hydra-cg.com
Chapter 122
Understanding Scopes
The scope of a service controls how long an instance of a service is used by the container. The
DependencyInjection component provides two generic scopes:
container (the default one):
The same instance is used each time you ask for it from this container.
prototype:
A new instance is created each time you ask for the service.
The ContainerAwareHttpKernel2 also defines a third scope: request. This scope is tied to the
request, meaning a new instance is created for each subrequest and is unavailable outside the request (for
instance in the CLI).
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/RequestStack.html#method_getCurrentRequest
2. http://api.symfony.com/2.7/Symfony/Component/HttpKernel/DependencyInjection/ContainerAwareHttpKernel.html
that belongs to it. This is not a common situation, but the idea is that you may enter and exit multiple
client scopes during a request, and each has its own client_configuration service.
Scopes add a constraint on the dependencies of a service: a service cannot depend on services from
a narrower scope. For example, if you create a generic my_foo service, but try to inject the
client_configuration service, you will receive a ScopeWideningInjectionException3 when
compiling the container. Read the sidebar below for more details.
A service can of course depend on a service from a wider scope without any issue.
3. http://api.symfony.com/2.7/Symfony/Component/DependencyInjection/Exception/ScopeWideningInjectionException.html
Prior to Symfony 2.7, there was another alternative based on synchronized services. However,
these kind of services have been deprecated starting from Symfony 2.7.
1
2
3
4
5
6
# app/config/services.yml
services:
my_mailer:
class: AppBundle\Mail\Mailer
scope: client
arguments: ['@client_configuration']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/AppBundle/Mail/Mailer.php
namespace AppBundle\Mail;
use Symfony\Component\DependencyInjection\ContainerInterface;
class Mailer
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function sendEmail()
{
$request = $this->container->get('client_configuration');
// ... do something using the client configuration here
}
}
Take care not to store the client configuration in a property of the object for a future call of the
service as it would cause the same issue described in the first section (except that Symfony cannot
detect that you are wrong).
The service configuration for this class would look something like this:
Listing 122-3
1
2
3
4
5
6
# app/config/services.yml
services:
my_mailer:
class:
AppBundle\Mail\Mailer
arguments: ['@service_container']
# scope: container can be omitted as it is the default
Injecting the whole container into a service is generally not a good idea (only inject what you need).
Chapter 123
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/Acme/MailerBundle/AcmeMailerBundle.php
namespace Acme\MailerBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Acme\MailerBundle\DependencyInjection\Compiler\CustomCompilerPass;
class AcmeMailerBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new CustomCompilerPass());
}
}
One of the most common use-cases of compiler passes is to work with tagged services (read more about
tags in the components section "Working with Tagged Services"). If you are using custom tags in a bundle
then by convention, tag names consist of the name of the bundle (lowercase, underscores as separators),
followed by a dot, and finally the "real" name. For example, if you want to introduce some sort of
"transport" tag in your AcmeMailerBundle, you should call it acme_mailer.transport.
Chapter 124
# app/config/services.yml
services:
app.session_handler:
class: AppBundle\Session\CustomSessionHandler
1
2
3
4
Finally, use the framework.session.handler_id configuration option to tell Symfony to use your
own session handler instead of the default one:
Listing 124-2
# app/config/config.yml
framework:
session:
# ...
handler_id: app.session_handler
1
2
3
4
5
Keep reading the next sections to learn how to use the session handlers in practice to solve two common
use cases: encrypt session information and define readonly guest sessions.
1
2
3
4
5
6
// src/AppBundle/Session/EncryptedSessionProxy.php
namespace AppBundle\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
class EncryptedSessionProxy extends SessionHandlerProxy
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Session/Storage/Proxy/SessionHandlerProxy.html
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
private $key;
public function __construct(\SessionHandlerInterface $handler, $key)
{
$this->key = $key;
parent::__construct($handler);
}
public function read($id)
{
$data = parent::read($id);
return mcrypt_decrypt(\MCRYPT_3DES, $this->key, $data);
}
public function write($id, $data)
{
$data = mcrypt_encrypt(\MCRYPT_3DES, $this->key, $data);
return parent::write($id, $data);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/AppBundle/Session/ReadOnlySessionProxy.php
namespace AppBundle\Session;
use AppBundle\Entity\User;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
class ReadOnlySessionProxy extends SessionHandlerProxy
{
private $user;
public function __construct(\SessionHandlerInterface $handler, User $user)
{
$this->user = $user;
parent::__construct($handler);
}
public function write($id, $data)
{
if ($this->user->isGuest()) {
return;
}
return parent::write($id, $data);
}
}
Chapter 125
Creating a LocaleListener
To simulate that the locale is stored in a session, you need to create and register a new event listener. The
listener will look something like this. Typically, _locale is used as a routing parameter to signify the
locale, though it doesn't really matter how you determine the desired locale from the request:
Listing 125-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/AppBundle/EventListener/LocaleListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
Chapter 125: Making the Locale "Sticky" during a User's Session | 428
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}
1
2
3
4
5
6
services:
app.locale_listener:
class: AppBundle\EventListener\LocaleListener
arguments: ['%kernel.default_locale%']
tags:
- { name: kernel.event_subscriber }
That's it! Now celebrate by changing the user's locale and seeing that it's sticky throughout the request.
Remember, to get the user's locale, always use the Request::getLocale1 method:
Listing 125-3
// from a controller...
use Symfony\Component\HttpFoundation\Request;
1
2
3
4
5
6
7
1
2
3
4
5
6
7
8
9
// src/AppBundle/EventListener/UserLocaleListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
/**
* Stores the locale of the user in the session after the
* login. This can be used by the LocaleListener afterwards.
1. http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Request.html#method_getLocale
Chapter 125: Making the Locale "Sticky" during a User's Session | 429
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
*/
class UserLocaleListener
{
/**
* @var Session
*/
private $session;
public function __construct(Session $session)
{
$this->session = $session;
}
/**
* @param InteractiveLoginEvent $event
*/
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if (null !== $user->getLocale()) {
$this->session->set('_locale', $user->getLocale());
}
}
}
1
2
3
4
5
6
7
# app/config/services.yml
services:
app.user_locale_listener:
class: AppBundle\EventListener\UserLocaleListener
arguments: ['@session']
tags:
- { name: kernel.event_listener, event: security.interactive_login, method: onInteractiveLogin }
In order to update the language immediately after a user has changed their language preferences, you
need to update the session after an update to the User entity.
Chapter 125: Making the Locale "Sticky" during a User's Session | 430
Chapter 126
1
2
3
4
5
# app/config/config.yml
framework:
session:
# handler_id set to null will use default session handler from php.ini
handler_id: ~
With this configuration, changing where your session metadata is stored is entirely up to your php.ini
configuration.
However, if you have the following configuration, Symfony will store the session data in files in the cache
directory %kernel.cache_dir%/sessions. This means that when you clear the cache, any current
sessions will also be deleted:
Listing 126-2
1
2
3
# app/config/config.yml
framework:
session: ~
Using a different directory to save session data is one method to ensure that your current sessions aren't
lost when you clear Symfony's cache.
Using a different session save handler is an excellent (yet more complex) method of session
management available within Symfony. See Configuring Sessions and Save Handlers for a discussion
of session save handlers. There are also entries in the cookbook about storing sessions in a relational
database or a NoSQL database.
To change the directory in which Symfony saves session data, you only need change the framework
configuration. In this example, you will change the session directory to app/sessions:
Listing 126-3
Chapter 126: Configuring the Directory where Session Files are Saved | 431
1
2
3
4
5
# app/config/config.yml
framework:
session:
handler_id: session.handler.native_file
save_path: '%kernel.root_dir%/sessions'
Chapter 126: Configuring the Directory where Session Files are Saved | 432
Chapter 127
1
2
3
4
framework:
session:
storage_id: session.storage.php_bridge
handler_id: ~
Otherwise, if the problem is simply that you cannot avoid the application starting the session with
session_start(), you can still make use of a Symfony based session save handler by specifying the
save handler as in the example below:
Listing 127-2
1
2
3
4
framework:
session:
storage_id: session.storage.php_bridge
handler_id: session.handler.native_file
If the legacy application requires its own session save handler, do not override this. Instead set
handler_id: ~. Note that a save handler cannot be changed once the session has been started.
If the application starts the session before Symfony is initialized, the save handler will have already
been set. In this case, you will need handler_id: ~. Only override the save handler if you are sure
the legacy application can use the Symfony save handler without side effects and that the session has
not been started before Symfony is initialized.
Chapter 128
1
2
3
framework:
session:
metadata_update_threshold: 120
PHP default's behavior is to save the session whether it has been changed or not. When using
framework.session.metadata_update_threshold Symfony will wrap the session handler
(configured at framework.session.handler_id) into the WriteCheckSessionHandler. This
will prevent any session write if the session was not modified.
Be aware that if the session is not written at every request, it may be garbage collected sooner than
usual. This means that your users may be logged out sooner than expected.
Chapter 129
1
2
3
4
5
Even if the user is not logged in and even if you haven't created any flash messages, just calling the
get() (or even has()) method of the flashBag will start a session. This may hurt your application
performance because all users will receive a session cookie. To avoid this behavior, add a check before
trying to access the flash messages:
Listing 129-2
1
2
3
4
5
6
7
{% if app.request.hasPreviousSession %}
{% for flashMessage in app.session.flashBag.get('notice') %}
<div class="flash-notice">
{{ flashMessage }}
</div>
{% endfor %}
{% endif %}
Chapter 130
Directory Structure
When looking at a Symfony2 project - for example, the Symfony Standard Edition1 - you'll notice a very
different directory structure than in symfony1. The differences, however, are somewhat superficial.
1. https://github.com/symfony/symfony-standard
Autoloading
One of the advantages of modern frameworks is never needing to worry about requiring files. By making
use of an autoloader, you can refer to any class in your project and trust that it's available. Autoloading
has changed in Symfony2 to be more universal, faster, and independent of needing to clear your cache.
In symfony1, autoloading was done by searching the entire project for the presence of PHP class files
and caching this information in a giant array. That array told symfony1 exactly which file contained each
class. In the production environment, this caused you to need to clear the cache when classes were added
or moved.
In Symfony2, a tool named Composer2 handles this process. The idea behind the autoloader is simple:
the name of your class (including the namespace) must match up with the path to the file containing that
class. Take the FrameworkExtraBundle from the Symfony2 Standard Edition as an example:
Listing 130-2
1
2
3
4
5
6
7
8
9
namespace Sensio\Bundle\FrameworkExtraBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
// ...
class SensioFrameworkExtraBundle extends Bundle
{
// ...
}
vendor/sensio/framework-extra-bundle/Sensio/Bundle/
FrameworkExtraBundle/SensioFrameworkExtraBundle.php. As you can see, the second part
The
file
itself
lives
at
of the path follows the namespace of the class. The first part is equal to the package name of the
SensioFrameworkExtraBundle.
The namespace, Sensio\Bundle\FrameworkExtraBundle, and package name, sensio/
framework-extra-bundle, spells out the directory that the file should live in (vendor/sensio/
framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle/). Composer can then
look for the file at this specific place and load it very fast.
the file did not live at this exact location, you'd receive a Class
"Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle" does not
exist. error. In Symfony2, a "class does not exist" error means that the namespace of the class and
If
physical location do not match. Basically, Symfony2 is looking in one exact location for that class, but
that location doesn't exist (or contains a different class). In order for a class to be autoloaded, you never
need to clear your cache in Symfony2.
As mentioned before, for the autoloader to work, it needs to know that the Sensio namespace lives
in the vendor/sensio/framework-extra-bundle directory and that, for example, the Doctrine
namespace lives in the vendor/doctrine/orm/lib/ directory. This mapping is entirely controlled by
Composer. Each third-party library you load through Composer has its settings defined and Composer
takes care of everything for you.
For this to work, all third-party libraries used by your project must be defined in the composer.json
file.
If you look at the HelloController from the Symfony Standard Edition you can see that it lives in
the Acme\DemoBundle\Controller namespace. Yet, the AcmeDemoBundle is not defined in your
composer.json file. Nonetheless are the files autoloaded. This is because you can tell Composer to
autoload files from specific directories without defining a dependency:
Listing 130-3
1
2
3
4
5
{
"autoload": {
"psr-0": { "": "src/" }
}
}
2. https://getcomposer.org
This means that if a class is not found in the vendor directory, Composer will search in the src
directory before throwing a "class does not exist" exception. Read more about configuring the Composer
autoloader in the Composer documentation3.
$ php symfony
In Symfony2, the console is now in the app sub-directory and is called console:
Listing 130-5
$ php app/console
Applications
In a symfony1 project, it is common to have several applications: one for the front-end and one for the
back-end for instance.
In a Symfony2 project, you only need to create one application (a blog application, an intranet
application, ...). Most of the time, if you want to create a second application, you might instead create
another project and share some bundles between them.
And if you need to separate the front-end and the back-end features of some bundles, you can create
sub-namespaces for controllers, sub-directories for templates, different semantic configurations, separate
routing configurations, and so on.
Of course, there's nothing wrong with having multiple applications in your project, that's entirely up to
you. A second application would mean a new directory, e.g. my_app/, with the same basic setup as the
app/ directory.
// config/ProjectConfiguration.class.php
public function setup()
{
// some plugins here
$this->enableAllPluginsExcept(array(...));
}
1
2
3
4
5
6
1
2
// app/AppKernel.php
public function registerBundles()
3. https://getcomposer.org/doc/04-schema.md#autoload
3
4
5
6
7
8
9
10
11
12
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
...,
new Acme\DemoBundle\AcmeDemoBundle(),
);
return $bundles;
}
Listing 130-8
# app/config/routing.yml
_hello:
resource: '@AcmeDemoBundle/Resources/config/routing.yml'
This will load the routes found in the Resources/config/routing.yml file of the
AcmeDemoBundle. The special @AcmeDemoBundle is a shortcut syntax that, internally, resolves to the
full path to that bundle.
You can use this same strategy to bring in configuration from a bundle:
1
2
3
Listing 130-9
# app/config/config.yml
imports:
- { resource: "@AcmeDemoBundle/Resources/config/config.yml" }
In Symfony2, configuration is a bit like app.yml in symfony1, except much more systematic. With
app.yml, you could simply create any keys you wanted. By default, these entries were meaningless and
depended entirely on how you used them in your application:
Listing 130-10 1
2
3
4
In Symfony2, you can also create arbitrary entries under the parameters key of your configuration:
Listing 130-11 1
parameters:
email.from_address: '[email protected]'
Listing 130-12
In reality, the Symfony2 configuration is much more powerful and is used primarily to configure objects
that you can use. For more information, see the chapter titled "Service Container".
Chapter 131
1
2
3
4
5
# app/config/config.yml
twig:
# ...
globals:
ga_tracking: UA-xxxxx-x
1
2
3
# app/config/parameters.yml
parameters:
ga_tracking: UA-xxxxx-x
Listing 131-4
1
2
3
4
# app/config/config.yml
twig:
globals:
ga_tracking: '%ga_tracking%'
Chapter 131: How to Inject Variables into all Templates (i.e. global Variables) | 441
Referencing Services
Instead of using static values, you can also set the value to a service. Whenever the global variable is
accessed in the template, the service will be requested from the service container and you get access to
that object.
The service is not loaded lazily. In other words, as soon as Twig is loaded, your service is instantiated,
even if you never use that global variable.
To define a service as a global Twig variable, prefix the string with @. This should feel familiar, as it's the
same syntax you use in service configuration.
Listing 131-5
1
2
3
4
5
# app/config/config.yml
twig:
# ...
globals:
user_management: '@app.user_management'
Chapter 131: How to Inject Variables into all Templates (i.e. global Variables) | 442
Chapter 132
1
2
{% extends "AppBundle::layout.html.twig" %}
{{ include('AppBundle:Foo:bar.html.twig') }}
1
2
{% extends "@App/layout.html.twig" %}
{{ include('@App/Foo/bar.html.twig') }}
1
2
3
# app/config/config.yml
twig:
# ...
Chapter 132: How to Use and Register Namespaced Twig Paths | 443
4
5
paths:
"%kernel.root_dir%/../vendor/acme/foo-bar/templates": foo_bar
Prior to 2.8, templates in custom namespaces are not pre-compiled by Symfony's cache warmup
process. They are compiled on demand. This may cause problems if two simultaneous requests are
trying to use the template for the first time.
{{ include('@foo_bar/sidebar.twig') }}
1
2
3
4
5
6
7
# app/config/config.yml
twig:
# ...
paths:
"%kernel.root_dir%/../vendor/acme/themes/theme1": theme
"%kernel.root_dir%/../vendor/acme/themes/theme2": theme
"%kernel.root_dir%/../vendor/acme/themes/common": theme
Now, you can use the same @theme namespace to refer to any template located in the previous three
directories:
Listing 132-6
{{ include('@theme/header.twig') }}
Chapter 132: How to Use and Register Namespaced Twig Paths | 444
Chapter 133
# app/config/config.yml
framework:
# ...
templating:
engines: ['twig', 'php']
1
2
3
4
5
You can now render a PHP template instead of a Twig one simply by using the .php extension in the
template name instead of .twig. The controller below renders the index.html.php template:
Listing 133-2
1
2
3
4
5
6
7
8
9
10
// src/AppBundle/Controller/HelloController.php
// ...
public function indexAction($name)
{
return $this->render(
'AppBundle:Hello:index.html.php',
array('name' => $name)
);
}
@Template1
AppBundle:Hello:index.html.php template:
You
Listing 133-3
1
2
can
also
use
the
shortcut
to
render
the
default
// src/AppBundle/Controller/HelloController.php
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
1. https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/view
Chapter 133: How to Use PHP instead of Twig for Templates | 445
3
4
5
6
7
8
9
10
11
12
// ...
/**
* @Template(engine="php")
*/
public function indexAction($name)
{
return array('name' => $name);
}
Enabling the php and twig template engines simultaneously is allowed, but it will produce an
undesirable side effect in your application: the @ notation for Twig namespaces will no longer be
supported for the render() method:
Listing 133-4
Listing 133-5
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
Decorating Templates
More often than not, templates in a project share common elements, like the well-known header and
footer. In Symfony, this problem is thought about differently: a template can be decorated by another
one.
The index.html.php template is decorated by layout.html.php, thanks to the extend() call:
Listing 133-6
1
2
3
4
The AppBundle::layout.html.php notation sounds familiar, doesn't it? It is the same notation
used to reference a template. The :: part simply means that the controller element is empty, so the
corresponding file is directly stored under views/.
Now, have a look at the layout.html.php file:
Listing 133-7
1
2
3
4
5
6
Chapter 133: How to Use PHP instead of Twig for Templates | 446
The layout is itself decorated by another one (::base.html.php). Symfony supports multiple
decoration levels: a layout can itself be decorated by another one. When the bundle part of the template
name is empty, views are looked for in the app/Resources/views/ directory. This directory stores
global views for your entire project:
Listing 133-8
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
The base layout already has the code to output the title in the header:
Listing 133-10 1
2
3
4
5
The output() method inserts the content of a slot and optionally takes a default value if the slot is not
defined. And _content is just a special slot that contains the rendered child template.
For large slots, there is also an extended syntax:
Listing 133-11 1
2
3
Chapter 133: How to Use PHP instead of Twig for Templates | 447
2
3
4
The render() method evaluates and returns the content of another template (this is the exact same
method as the one used in the controller).
2
3
4
5
6
7
Here, the AppBundle:Hello:fancy string refers to the fancy action of the Hello controller:
Listing 133-15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Controller/HelloController.php
class HelloController extends Controller
{
public function fancyAction($name, $color)
{
// create some object, based on the $color variable
$object = ...;
return $this->render('AppBundle:Hello:fancy.html.php', array(
'name'
=> $name,
'object' => $object
));
}
// ...
}
But where is the $view['actions'] array element defined? Like $view['slots'], it's called a
template helper, and the next section tells you more about those.
Chapter 133: How to Use PHP instead of Twig for Templates | 448
2
3
The generate() method takes the route name and an array of parameters as arguments. The route
name is the main key under which routes are referenced and the parameters are the values of the
placeholders defined in the route pattern:
Listing 133-17 1
2
3
4
# src/AppBundle/Resources/config/routing.yml
hello: # The route name
path:
/hello/{name}
defaults: { _controller: AppBundle:Hello:index }
2
3
The assets helper's main purpose is to make your application more portable. Thanks to this helper,
you can move the application root directory anywhere under your web root directory without changing
anything in your template's code.
Profiling Templates
By using the stopwatch helper, you are able to time parts of your template and display it on the timeline
of the WebProfilerBundle:
<?php $view['stopwatch']->start('foo') ?>
... things that get timed
<?php $view['stopwatch']->stop('foo') ?>
Listing 133-19
If you use the same name more than once in your template, the times are grouped on the same line
in the timeline.
Output Escaping
When using PHP templates, escape variables whenever they are displayed to the user:
<?php echo $view->escape($var) ?>
Listing 133-20
By default, the escape() method assumes that the variable is outputted within an HTML context. The
second argument lets you change the context. For instance, to output something in a JavaScript script,
use the js context:
<?php echo $view->escape($var, 'js') ?>
Listing 133-21
Chapter 133: How to Use PHP instead of Twig for Templates | 449
Chapter 134
To get your custom functionality you must first create a Twig Extension class. As an example you'll create
a price filter to format a given number into price:
Listing 134-1
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}
1. https://github.com/twigphp/Twig-extensions
2. http://twig.sensiolabs.org/doc/advanced_legacy.html#creating-an-extension
13
14
15
16
17
18
19
20
21
22
23
24
25
Along with custom filters, you can also add custom functions and register global variables.
1
2
3
4
5
6
7
# app/config/services.yml
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
1
2
{# outputs $5,500.00 #}
{{ '5500'|price }}
1
2
{# outputs $5500,2516 #}
{{ '5500.25155'|price(4, ',', '') }}
Learning further
For a more in-depth look into Twig Extensions, please take a look at the Twig extensions documentation3.
3. http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension
Chapter 135
1
2
3
4
5
acme_privacy:
path: /privacy
defaults:
_controller: FrameworkBundle:Template:template
template:
static/privacy.html.twig
{{ render(url('acme_privacy')) }}
1
2
3
4
5
6
7
acme_privacy:
path: /privacy
defaults:
_controller:
template:
maxAge:
sharedAge:
FrameworkBundle:Template:template
'static/privacy.html.twig'
86400
86400
The maxAge and sharedAge values are used to modify the Response object created in the controller.
For more information on caching, see HTTP Cache.
There is also a private variable (not shown here). By default, the Response will be made public, as long
as maxAge or sharedAge are passed. If set to true, the Response will be marked as private.
Chapter 136
When your application is using a form_login, you can simplify your tests by allowing your test
configuration to make use of HTTP authentication. This way you can use the above to authenticate
in tests, but still have your users log in via the normal form_login. The trick is to include the
http_basic key in your firewall, along with the form_login key:
Listing 136-3
1
2
3
4
5
# app/config/config_test.yml
security:
firewalls:
your_firewall_name:
http_basic: ~
Chapter 137
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Tests/Controller/DefaultControllerTest.php
namespace Appbundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class DefaultControllerTest extends WebTestCase
{
private $client = null;
public function setUp()
{
$this->client = static::createClient();
}
public function testSecuredHello()
{
$this->logIn();
$crawler = $this->client->request('GET', '/admin');
$this->assertTrue($this->client->getResponse()->isSuccessful());
$this->assertGreaterThan(0, $crawler->filter('html:contains("Admin Dashboard")')->count());
}
private function logIn()
{
$session = $this->client->getContainer()->get('session');
Chapter 137: How to Simulate Authentication with a Token in a Functional Test | 455
31
32
33
34
35
36
37
38
39
40
41
The technique described in How to Simulate HTTP Authentication in a Functional Test is cleaner and
therefore the preferred way.
Chapter 137: How to Simulate Authentication with a Token in a Functional Test | 456
Chapter 138
1
2
3
4
5
6
7
8
9
10
// ...
$harry = static::createClient();
$sally = static::createClient();
$harry->request('POST', '/say/sally/Hello');
$sally->request('GET', '/messages');
$this->assertEquals(Response::HTTP_CREATED, $harry->getResponse()->getStatusCode());
$this->assertRegExp('/Hello/', $sally->getResponse()->getContent());
This works except when your code maintains a global state or if it depends on a third-party library that
has some kind of global state. In such a case, you can insulate your clients:
Listing 138-2
1
2
3
4
5
6
7
8
9
10
11
12
13
// ...
$harry = static::createClient();
$sally = static::createClient();
$harry->insulate();
$sally->insulate();
$harry->request('POST', '/say/sally/Hello');
$sally->request('GET', '/messages');
$this->assertEquals(Response::HTTP_CREATED, $harry->getResponse()->getStatusCode());
$this->assertRegExp('/Hello/', $sally->getResponse()->getContent());
Insulated clients transparently execute their requests in a dedicated and clean PHP process, thus avoiding
any side-effects.
As an insulated client is slower, you can keep one client in the main process, and insulate the other
ones.
Chapter 139
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
If a test fails because of profiling data (too many DB queries for instance), you might want to use the Web
Profiler to analyze the request after the tests finish. It's easy to achieve if you embed the token in the error
message:
PDF brought to you by
generated on July 28, 2016
Listing 139-2
1
2
3
4
5
6
7
8
$this->assertLessThan(
30,
$profile->getCollector('db')->getQueryCount(),
sprintf(
'Checks that query count is less than 30 (token %s)',
$profile->getToken()
)
);
The profiler store can be different depending on the environment (especially if you use the SQLite
store, which is the default configured one).
The profiler information is available even if you insulate the client or if you use an HTTP layer for
your tests.
Read the API for built-in data collectors to learn more about their interfaces.
1
2
3
4
5
6
7
# app/config/config_test.yml
# ...
framework:
profiler:
enabled: true
collect: false
In this way only tests that call $client->enableProfiler() will collect data.
Chapter 140
1
2
3
4
5
6
namespace AppBundle\Salary;
use Doctrine\Common\Persistence\ObjectManager;
class SalaryCalculator
{
Chapter 140: How to Test Code that Interacts with the Database | 460
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private $entityManager;
public function __construct(ObjectManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function calculateTotalSalary($id)
{
$employeeRepository = $this->entityManager
->getRepository('AppBundle:Employee');
$employee = $employeeRepository->find($id);
return $employee->getSalary() + $employee->getBonus();
}
}
Since the ObjectManager gets injected into the class through the constructor, it's easy to pass a mock
object within a test:
Listing 140-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use AppBundle\Salary\SalaryCalculator;
class SalaryCalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testCalculateTotalSalary()
{
// First, mock the object to be used in the test
$employee = $this->getMock('\AppBundle\Entity\Employee');
$employee->expects($this->once())
->method('getSalary')
->will($this->returnValue(1000));
$employee->expects($this->once())
->method('getBonus')
->will($this->returnValue(1100));
In this example, you are building the mocks from the inside out, first creating the employee which gets
returned by the Repository, which itself gets returned by the EntityManager. This way, no real class
is involved in testing.
Chapter 140: How to Test Code that Interacts with the Database | 461
1
2
3
4
5
6
7
8
# app/config/config_test.yml
doctrine:
# ...
dbal:
host:
localhost
dbname:
testdb
user:
testdb
password: testdb
Make sure that your database runs on localhost and has the defined database and user credentials set up.
Chapter 140: How to Test Code that Interacts with the Database | 462
Chapter 141
Functional Testing
If you need to actually execute a query, you will need to boot the kernel to get a valid connection. In this
case, you'll extend the KernelTestCase, which makes all of this quite easy:
Listing 141-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/AppBundle/Tests/Entity/ProductRepositoryFunctionalTest.php
namespace AppBundle\Tests\Entity;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class ProductRepositoryFunctionalTest extends KernelTestCase
{
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
/**
* {@inheritDoc}
*/
protected function setUp()
{
self::bootKernel();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager()
;
}
public function testSearchByCategoryName()
{
$products = $this->em
->getRepository('AppBundle:Product')
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
->searchByCategoryName('foo')
;
$this->assertCount(1, $products);
}
/**
* {@inheritDoc}
*/
protected function tearDown()
{
parent::tearDown();
$this->em->close();
$this->em = null; // avoid memory leaks
}
}
Chapter 142
1
2
3
4
5
6
7
8
9
10
// app/tests.bootstrap.php
if (isset($_ENV['BOOTSTRAP_CLEAR_CACHE_ENV'])) {
passthru(sprintf(
'php "%s/console" cache:clear --env=%s --no-warmup',
__DIR__,
$_ENV['BOOTSTRAP_CLEAR_CACHE_ENV']
));
}
require __DIR__.'/bootstrap.php.cache';
1
2
3
4
5
6
Now, you can define in your phpunit.xml.dist file which environment you want the cache to be
cleared:
Listing 142-3
1
2
3
4
Chapter 142: How to Customize the Bootstrap Process before Running Tests | 465
This now becomes an environment variable (i.e. $_ENV) that's available in the custom bootstrap file
(tests.bootstrap.php).
Chapter 142: How to Customize the Bootstrap Process before Running Tests | 466
Chapter 143
That's it! You should not encounter any backwards-compatibility breaks or need to change anything else
in your code. That's because when you started your project, your composer.json included Symfony
using a constraint like 2.6.*, where only the last version number will change when you update.
It is recommended to update to a new patch version as soon as possible, as important bugs and
security leaks may be fixed in these new releases.
$ composer update
Beware, if you have some unspecific version constraints2 in your composer.json (e.g. devmaster), this could upgrade some non-Symfony libraries to new versions that contain backwardscompatibility breaking changes.
1. https://getcomposer.org/doc/01-basic-usage.md#package-versions
2. https://getcomposer.org/doc/01-basic-usage.md#package-versions
Chapter 144
1
2
3
4
5
6
7
8
{
"...": "...",
"require": {
"symfony/symfony": "2.6.*",
},
"...": "...",
}
Dependency Errors
If you get a dependency error, it may simply mean that you need to upgrade other Symfony dependencies
too. In that case, try the following command:
Listing 144-3
This updates symfony/symfony and all packages that it depends on, which will include several other
packages. By using tight version constraints in composer.json, you can control what versions each
library upgrades to.
If this still doesn't work, your composer.json file may specify a version for a library that is not
compatible with the newer Symfony version. In that case, updating that library to a newer version in
composer.json may solve the issue.
Or, you may have deeper issues where different libraries depend on conflicting versions of other libraries.
Check your error message to debug.
$ composer update
Beware, if you have some unspecific version constraints2 in your composer.json (e.g. devmaster), this could upgrade some non-Symfony libraries to new versions that contain backwardscompatibility breaking changes.
1. https://getcomposer.org/doc/01-basic-usage.md#package-versions
2. https://getcomposer.org/doc/01-basic-usage.md#package-versions
3. https://github.com/symfony/symfony/blob/2.7/UPGRADE-2.7.md
4. https://github.com/symfony/symfony
Chapter 145
Of course ultimately, you want to stop using the deprecated functionality. Sometimes, this is easy: the
warning might tell you exactly what to change.
But other times, the warning might be unclear: a setting somewhere might cause a class deeper to trigger
the warning. In this case, Symfony does its best to give a clear message, but you may need to research
that warning further.
And sometimes, the warning may come from a third-party library or bundle that you're using. If that's
true, there's a good chance that those deprecations have already been updated. In that case, upgrade the
library to fix them.
Once all the deprecation warnings are gone, you can upgrade with a lot more confidence.
Deprecations in PHPUnit
When you run your tests using PHPUnit, no deprecation notices are shown. To help you here, Symfony
provides a PHPUnit bridge. This bridge will show you a nice summary of all deprecation notices at the
end of the test report.
All you need to do is install the PHPUnit bridge:
Listing 145-1
1
2
3
4
5
6
7
8
9
10
11
12
13
$ phpunit
...
OK (10 tests, 20 assertions)
Remaining deprecation notices (6)
The "request" service is deprecated and will be removed in 3.0. Add a typehint for
Symfony\Component\HttpFoundation\Request to your controller parameters to retrieve the
request instead: 6x
3x in PageAdminTest::testPageShow from Symfony\Cmf\SimpleCmsBundle\Tests\WebTest\Admin
2x in PageAdminTest::testPageList from Symfony\Cmf\SimpleCmsBundle\Tests\WebTest\Admin
1x in PageAdminTest::testPageEdit from Symfony\Cmf\SimpleCmsBundle\Tests\WebTest\Admin
Once you fixed them all, the command ends with 0 (success) and you're done!
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
{
"...": "...",
"require": {
"symfony/symfony": "3.0.*",
},
"...": "..."
}
Dependency Errors
If you get a dependency error, it may simply mean that you need to upgrade other Symfony dependencies
too. In that case, try the following command:
Listing 145-6
This updates symfony/symfony and all packages that it depends on, which will include several other
packages. By using tight version constraints in composer.json, you can control what versions each
library upgrades to.
If this still doesn't work, your composer.json file may specify a version for a library that is not
compatible with the newer Symfony version. In that case, updating that library to a newer version in
composer.json may solve the issue.
Or, you may have deeper issues where different libraries depend on conflicting versions of other libraries.
Check your error message to debug.
$ composer update
Beware, if you have some unspecific version constraints2 in your composer.json (e.g. devmaster), this could upgrade some non-Symfony libraries to new versions that contain backwardscompatibility breaking changes.
1. https://getcomposer.org/doc/01-basic-usage.md#package-versions
2. https://getcomposer.org/doc/01-basic-usage.md#package-versions
Chapter 146
1
2
3
4
5
6
7
{
"require": {
"symfony/framework-bundle": "~2.7",
"symfony/finder": "~2.7",
"symfony/validator": "~2.7"
}
}
These constraints prevent the bundle from using Symfony 3 components, so it makes it impossible to
install it in a Symfony 3 based application. This issue is very easy to solve thanks to the flexibility of
Composer dependencies constraints. Just replace ~2.N by ~2.N|~3.0 (or ^2.N by ^2.N|~3.0).
The above example can be updated to work with Symfony 3 as follows:
Listing 146-2
1
2
3
4
5
6
7
{
"require": {
"symfony/framework-bundle": "~2.7|~3.0",
"symfony/finder": "~2.7|~3.0",
"symfony/validator": "~2.7|~3.0"
}
}
Chapter 146: Upgrading a Third-Party Bundle for a Major Symfony Version | 474
Another common version constraint found on third-party bundles is >=2.N. You should avoid using
that constraint because it's too generic (it means that your bundle is compatible with any future
Symfony version). Use instead ~2.N|~3.0 or ^2.N|~3.0 to make your bundle future-proof.
Then, run your test suite and look for the deprecation list displayed after the PHPUnit test report:
Listing 146-4
1
2
3
4
5
6
7
8
9
10
11
12
13
$ phpunit
Fix the reported deprecations, run the test suite again and repeat the process until no deprecation usage
is reported.
Useful Resources
There are several resources that can help you detect, understand and fix the use of deprecated features:
Official Symfony Guide to Upgrade from 2.x to 3.02
The full list of changes required to upgrade to Symfony 3.0 and grouped by component.
SensioLabs DeprecationDetector3
It runs a static code analysis against your project's source code to find usages of deprecated methods,
classes and interfaces. It works for any PHP application, but it includes special detectors for
Symfony applications, where it can also detect usages of deprecated services.
Symfony Upgrade Fixer4
It analyzes Symfony projects to find deprecations. In addition it solves automatically some of them
thanks to the growing list of supported "fixers".
1. https://github.com/symfony/phpunit-bridge
2. https://github.com/symfony/symfony/blob/2.8/UPGRADE-3.0.md
3. https://github.com/sensiolabs-de/deprecation-detector
4. https://github.com/umpirsky/Symfony-Upgrade-Fixer
Chapter 146: Upgrading a Third-Party Bundle for a Major Symfony Version | 475
$ ln -s /path/to/your/local/bundle/ vendor/you-vendor-name/your-bundle-name
If your operating system doesn't support symbolic links, you'll need to copy your local bundle directory
into the appropriate directory inside vendor/.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
language: php
sudo: false
php:
- 5.3
- 5.6
- 7.0
matrix:
include:
- php:
env:
- php:
env:
- php:
env:
- php:
env:
- php:
env:
- php:
env:
5.3.3
COMPOSER_FLAGS='--prefer-lowest --prefer-stable' SYMFONY_DEPRECATIONS_HELPER=weak
5.6
SYMFONY_VERSION='2.7.*'
5.6
SYMFONY_VERSION='2.8.*'
5.6
SYMFONY_VERSION='3.0.*'
5.6
SYMFONY_VERSION='3.1.*'
5.6
DEPENDENCES='dev' SYMFONY_VERSION='3.2.*@dev'
before_install:
- composer self-update
- if [ "$DEPENDENCIES" == "dev" ]; then perl -pi -e 's/^}$/,"minimum-stability":"dev"}/' composer.json;
fi;
- if [ "$SYMFONY_VERSION" != "" ]; then composer --no-update require symfony/symfony:${SYMFONY_VERSION};
fi;
install: composer update $COMPOSER_FLAGS
script: phpunit
Updating your Code to Support Symfony 2.x and 3.x at the Same Time
The real challenge of adding Symfony 3 support for your bundles is when you want to support both
Symfony 2.x and 3.x simultaneously using the same code. There are some edge cases where you'll need
to deal with the API differences.
Before diving into the specifics of the most common edge cases, the general recommendation is to not
rely on the Symfony Kernel version to decide which code to use:
Chapter 146: Upgrading a Third-Party Bundle for a Major Symfony Version | 476
Listing 146-7
1
2
3
4
5
Instead of checking the Symfony Kernel version, check the version of the specific component. For
example, the OptionsResolver API changed in its 2.6 version by adding a setDefined() method. The
recommended check in this case would be:
Listing 146-8
1
2
3
4
5
if (!method_exists('Symfony\Component\OptionsResolver\OptionsResolver', 'setDefined')) {
// code for the old OptionsResolver API
} else {
// code for the new OptionsResolver API
}
Chapter 146: Upgrading a Third-Party Bundle for a Major Symfony Version | 477
Chapter 147
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Validator/Constraints/ContainsAlphanumeric.php
namespace AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ContainsAlphanumeric extends Constraint
{
public $message = 'The string "%string%" contains an illegal character: it can only contain letters or
numbers.';
}
The @Annotation annotation is necessary for this new constraint in order to make it available for
use in classes via annotations. Options for your constraint are represented as public properties on
the constraint class.
1. http://api.symfony.com/2.7/Symfony/Component/Validator/Constraint.html
2. http://api.symfony.com/2.7/Symfony/Component/Validator/Constraint.html
1
2
3
4
5
In other words, if you create a custom Constraint (e.g. MyConstraint), Symfony will automatically
look for another class, MyConstraintValidator when actually performing the validation.
The validator class is also simple, and only has one required method validate():
Listing 147-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/AppBundle/Validator/Constraints/ContainsAlphanumericValidator.php
namespace AppBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ContainsAlphanumericValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
// If you're using the new 2.5 validation API (you probably are!)
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $value)
->addViolation();
Inside validate, you don't need to return a value. Instead, you add violations to the validator's
context property and a value will be considered valid if it causes no violations. The buildViolation
method takes the error message as its argument and returns an instance of
ConstraintViolationBuilderInterface3. The addViolation method call finally adds the
violation to the context.
1
2
3
4
5
// src/AppBundle/Entity/AcmeEntity.php
use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Validator\Constraints as AcmeAssert;
class AcmeEntity
3. http://api.symfony.com/2.7/Symfony/Component/Validator/Violation/ConstraintViolationBuilderInterface.html
6
7
8
9
10
11
12
13
14
15
16
// ...
/**
* @Assert\NotBlank
* @AcmeAssert\ContainsAlphanumeric
*/
protected $name;
// ...
}
If your constraint contains options, then they should be public properties on the custom Constraint class
you created earlier. These options can be configured like options on core Symfony constraints.
1
2
3
4
5
6
# app/config/services.yml
services:
validator.unique.your_validator_name:
class: Fully\Qualified\Validator\Class\Name
tags:
- { name: validator.constraint_validator, alias: alias_name }
As mentioned above, Symfony will automatically look for a class named after the constraint, with
Validator appended. You can override this in your constraint class:
Listing 147-6
Make sure to use the 'alias_name' when you have configured your validator as a service. Otherwise your
validator class will be simply instantiated without your dependencies.
With this, the validator validate() method gets an object as its first argument:
Listing 147-8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Note that a class constraint validator is applied to the class itself, and not to the property:
Listing 147-9
1
2
3
4
5
6
7
/**
* @AcmeAssert\ContainsAlphanumeric
*/
class AcmeEntity
{
// ...
}
Chapter 148
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class User
{
/**
* @Assert\NotBlank(payload = {"severity" = "error"})
*/
protected $username;
/**
* @Assert\NotBlank(payload = {"severity" = "error"})
*/
protected $password;
/**
* @Assert\Iban(payload = {"severity" = "warning"})
*/
protected $bankAccountNumber;
}
1
2
3
4
5
For example, you can leverage this to customize the form_errors block so that the severity is added as
an additional HTML class:
Listing 148-3
1
2
3
4
5
6
7
8
9
10
11
12
For more information on customizing form rendering, see How to Customize Form Rendering.
1. http://api.symfony.com/2.7/Symfony/Component/Validator/ConstraintViolation.html#method_getConstraint
Chapter 149
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/AppBundle/Validation/ValidationGroupResolver.php
namespace AppBundle\Validation;
use Symfony\Component\Form\FormInterface;
class ValidationGroupResolver
{
private $service1;
private $service2;
public function __construct($service1, $service2)
{
$this->service1 = $service1;
$this->service2 = $service2;
}
/**
* @param FormInterface $form
* @return array
*/
public function __invoke(FormInterface $form)
{
$groups = array();
// ... determine which groups to apply and return an array
return $groups;
}
}
Then in your form, inject the resolver and set it as the validation_groups.
Listing 149-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/AppBundle/Form/MyClassType.php;
namespace AppBundle\Form;
use AppBundle\Validator\ValidationGroupResolver;
use Symfony\Component\Form\AbstractType
use Symfony\Component\OptionsResolver\OptionsResolver;
class MyClassType extends AbstractType
{
private $groupResolver;
public function __construct(ValidationGroupResolver $groupResolver)
{
$this->groupResolver = $groupResolver;
}
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => $this->groupResolver,
));
}
}
This will result in the form validator invoking your group resolver to set the validation groups returned
when validating.
Chapter 150
This starts the web server at localhost:8000 in the background that serves your Symfony application.
By default, the web server listens on port 8000 on the loopback device. You can change the socket passing
an IP address and a port as a command-line argument:
Listing 150-2
1. http://www.php.net/manual/en/features.commandline.webserver.php
You can use the server:status command to check if a web server is listening on a certain socket:
Listing 150-3
1
2
3
The first command shows if your Symfony application will be server through localhost:8000,
the second one does the same for 192.168.0.1:8080.
Before Symfony 2.6, the server:run command was used to start the built-in web server. This
command is still available and behaves slightly different. Instead of starting the server in the
background, it will block the current terminal until you terminate it (this is usually done by pressing
Ctrl and C).
You should NEVER listen to all interfaces on a computer that is directly accessible from the
Internet. The built-in web server is not designed to be used on public networks.
Command Options
The built-in web server expects a "router" script (read about the "router" script on php.net2) as an
argument. Symfony already passes such a router script when the command is executed in the prod or
in the dev environment. Use the --router option in any other environment or to use another router
script:
Listing 150-5
If your application's document root differs from the standard directory layout, you have to pass the
correct location using the --docroot option:
Listing 150-6
2. http://php.net/manual/en/features.commandline.webserver.php#example-411
Like with the start command, if you omit the socket information, Symfony will stop the web server bound
to localhost:8000. Just pass the socket information when the web server listens to another IP address
or to another port:
Listing 150-8
Chapter 151
SOAP works by exposing the methods of a PHP object to an external entity (i.e. the person using the
SOAP service). To start, create a class - HelloService - which represents the functionality that you'll
expose in your SOAP service. In this case, the SOAP service will allow the client to call a method called
hello, which happens to send an email:
Listing 151-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/Acme/SoapBundle/Services/HelloService.php
namespace Acme\SoapBundle\Services;
class HelloService
{
private $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function hello($name)
{
$message = \Swift_Message::newInstance()
->setTo('[email protected]')
1. http://php.net/manual/en/book.soap.php
2. http://framework.zend.com/manual/current/en/modules/zend.soap.server.html
3. http://sourceforge.net/projects/nusoap
Chapter 151: How to Create a SOAP Web Service in a Symfony Controller | 489
18
19
20
21
22
23
24
25
->setSubject('Hello Service')
->setBody($name . ' says hi!');
$this->mailer->send($message);
return 'Hello, '.$name;
}
}
Next, you can train Symfony to be able to create an instance of this class. Since the class sends an email,
it's been designed to accept a Swift_Mailer instance. Using the Service Container, you can configure
Symfony to construct a HelloService object properly:
Listing 151-2
1
2
3
4
5
# app/config/services.yml
services:
hello_service:
class: Acme\SoapBundle\Services\HelloService
arguments: ['@mailer']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace Acme\SoapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class HelloServiceController extends Controller
{
public function indexAction()
{
$server = new \SoapServer('/path/to/hello.wsdl');
$server->setObject($this->get('hello_service'));
$response = new Response();
$response->headers->set('Content-Type', 'text/xml; charset=ISO-8859-1');
ob_start();
$server->handle();
$response->setContent(ob_get_clean());
return $response;
}
}
Take note of the calls to ob_start() and ob_get_clean(). These methods control output buffering4
which allows you to "trap" the echoed output of $server->handle(). This is necessary because
Symfony expects your controller to return a Response object with the output as its "content". You must
also remember to set the "Content-Type" header to "text/xml", as this is what the client will expect. So,
you use ob_start() to start buffering the STDOUT and use ob_get_clean() to dump the echoed
output into the content of the Response and clear the output buffer. Finally, you're ready to return the
Response.
Below is an example calling the service using a NuSOAP5 client. This example assumes that the
indexAction in the controller above is accessible via the route /soap:
Listing 151-4
4. http://php.net/manual/en/book.outcontrol.php
5. http://sourceforge.net/projects/nusoap
Chapter 151: How to Create a SOAP Web Service in a Symfony Controller | 490
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Chapter 151: How to Create a SOAP Web Service in a Symfony Controller | 491
Chapter 152
Though this entry is specifically about Git, the same generic principles will apply if you're storing
your project in Subversion.
Once you've read through Create your First Page in Symfony and become familiar with using Symfony,
you'll no-doubt be ready to start your own project. In this cookbook article, you'll learn the best way to
start a new Symfony project that's stored using the Git1 source control management system.
$ git init
$ git add .
1. http://git-scm.com/
Chapter 152: How to Create and Store a Symfony Project in Git | 492
As you might have noticed, not all files that were downloaded by Composer in step
1, have been staged for commit by Git. Certain files and folders, such as the project's
dependencies (which are managed by Composer), parameters.yml (which contains
sensitive information such as database credentials), log and cache files and dumped assets
(which are created automatically by your project), should not be committed in Git. To
help you prevent committing those files and folders by accident, the Standard Distribution
comes with a file called .gitignore, which contains a list of files and folders that Git
should ignore.
You may also want to create a .gitignore file that can be used system-wide. This allows
you to exclude files/folders for all your projects that are created by your IDE or operating
system. For details, see GitHub .gitignore2.
At this point, you have a fully-functional Symfony project that's correctly committed to Git. You can
immediately begin development, committing the new changes to your Git repository.
You can continue to follow along with the Create your First Page in Symfony chapter to learn more about
how to configure and develop inside your application.
The Symfony Standard Edition comes with some example functionality. To remove the sample code,
follow the instructions in the "How to Remove the AcmeDemoBundle" article.
2. https://help.github.com/articles/ignoring-files
3. https://getcomposer.org/
Chapter 152: How to Create and Store a Symfony Project in Git | 493
Upgrading Symfony
Since Symfony is just a group of third-party libraries and third-party libraries are entirely controlled
through composer.json and composer.lock, upgrading Symfony means simply upgrading
each of these files to match their state in the latest Symfony Standard Edition.
Of course, if you've added new entries to composer.json, be sure to replace only the original parts
(i.e. be sure not to also delete any of your custom entries).
4. https://getcomposer.org/
5. https://github.com/
6. https://bitbucket.org/
7. https://en.wikipedia.org/wiki/Comparison_of_open-source_software_hosting_facilities
8. http://git-scm.com/book/en/Git-Basics-Getting-a-Git-Repository
9. https://github.com/sitaramc/gitolite
Chapter 152: How to Create and Store a Symfony Project in Git | 494
Chapter 153
This entry is specifically about Subversion, and based on principles found in How to Create and Store
a Symfony Project in Git.
Once you've read through Create your First Page in Symfony and become familiar with using Symfony,
you'll no-doubt be ready to start your own project. The preferred method to manage Symfony projects is
using Git1 but some prefer to use Subversion2 which is totally fine!. In this cookbook article, you'll learn
how to manage your project using SVN3 in a similar manner you would do with Git4.
This is a method to tracking your Symfony project in a Subversion repository. There are several ways
to do and this one is simply one that works.
1
2
3
4
myproject/
branches/
tags/
trunk/
1. http://git-scm.com/
2. http://subversion.apache.org/
3. http://subversion.apache.org/
4. http://git-scm.com/
Chapter 153: How to Create and Store a Symfony Project in Subversion | 495
Most Subversion hosting should follow this standard practice. This is the recommended layout in
Version Control with Subversion5 and the layout used by most free hosting (see Subversion Hosting
Solutions).
$ mv Symfony/* myproject/
3. Now, set the ignore rules. Not everything should be stored in your Subversion repository. Some
files (like the cache) are generated and others (like the database configuration) are meant to be
customized on each machine. This makes use of the svn:ignore property, so that specific files
can be ignored.
Listing 153-4
1
2
3
4
5
6
7
8
9
10
11
12
$ cd myproject/
$ svn add --depth=empty app app/cache app/logs app/config web
$
$
$
$
$
svn
svn
svn
svn
svn
propset
propset
propset
propset
propset
svn:ignore
svn:ignore
svn:ignore
svn:ignore
svn:ignore
"vendor" .
"bootstrap*" app/
"parameters.yml" app/config/
"*" app/cache/
"*" app/logs/
4. The rest of the files can now be added and committed to the project:
Listing 153-5
1
2
That's it! Since the app/config/parameters.yml file is ignored, you can store machine-specific
settings like database passwords here without committing them. The parameters.yml.dist file is
committed, but is not read by Symfony. And by adding any new keys you need to both files, new
developers can quickly clone the project, copy this file to parameters.yml, customize it, and start
developing.
At this point, you have a fully-functional Symfony project stored in your Subversion repository. The
development can start with commits in the Subversion repository.
You can continue to follow along with the Create your First Page in Symfony chapter to learn more about
how to configure and develop inside your application.
5. http://svnbook.red-bean.com/
6. http://code.google.com/hosting/
Chapter 153: How to Create and Store a Symfony Project in Subversion | 496
The Symfony Standard Edition comes with some example functionality. To remove the sample code,
follow the instructions in the "How to Remove the AcmeDemoBundle" article.
Upgrading Symfony
Since Symfony is just a group of third-party libraries and third-party libraries are entirely controlled
through composer.json and composer.lock, upgrading Symfony means simply upgrading
each of these files to match their state in the latest Symfony Standard Edition.
Of course, if you've added new entries to composer.json, be sure to replace only the original parts
(i.e. be sure not to also delete any of your custom entries).
7. https://getcomposer.org/
8. https://getcomposer.org/
Chapter 153: How to Create and Store a Symfony Project in Subversion | 497
9. http://git-scm.com/
10. http://subversion.apache.org/
11. https://github.com/
12. http://code.google.com/hosting/
13. http://sourceforge.net/
14. http://gna.org/
Chapter 153: How to Create and Store a Symfony Project in Subversion | 498
Chapter 154
1
2
3
4
# ...
folders:
- map: ~/projects
to: /home/vagrant/projects
1. http://laravel.com/docs/homestead
2. https://www.vagrantup.com/
3. http://php.net/manual/en/function.sys-get-temp-dir.php
4. http://www.whitewashing.de/2013/08/19/speedup_symfony2_on_vagrant_boxes.html
5. http://laravel.com/docs/homestead#installation-and-setup
1
2
3
4
5
# ...
sites:
- map: symfony-demo.dev
to: /home/vagrant/projects/symfony_demo/web
type: symfony
The type option tells Homestead to use the Symfony nginx configuration.
At last, edit the hosts file on your local machine to map symfony-demo.dev to 192.168.10.10
(which is the IP used by Homestead):
Listing 154-3
Now, navigate to http://symfony-demo.dev in your web browser and enjoy developing your
Symfony application!
To learn more features of Homestead, including Blackfire Profiler integration, automatic creation of MySQL
databases and more, read the Daily Usage6 section of the Homestead documentation.
6. http://laravel.com/docs/5.1/homestead#daily-usage