Symfony Cookbook 2.3
Symfony Cookbook 2.3
Symfony Cookbook 2.3
The Cookbook (2.3) This work is licensed under the Attribution-Share Alike 3.0 Unported license (http://creativecommons.org/ licenses/by-sa/3.0/). You are free to share (to copy, distribute and transmit the work), and to remix (to adapt the work) under the following conditions: Attribution: You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike: If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. For any reuse or distribution, you must make clear to others the license terms of this work. The information in this book is distributed on an as is basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor SensioLabs shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. If you find typos or errors, feel free to report them by creating a ticket on the Symfony ticketing system (http://github.com/symfony/symfony-docs/issues). Based on tickets and users feedback, this book is continuously updated.
Contents at a Glance
How to Use Assetic for Asset Management ..........................................................................................6 How to Minify CSS/JS Files (using UglifyJs and UglifyCss).................................................................11 How to Minify JavaScripts and Stylesheets with YUI Compressor.......................................................15 How to Use Assetic For Image Optimization with Twig Functions .....................................................17 How to Apply an Assetic Filter to a Specific File Extension.................................................................20 How to install 3rd party Bundles .......................................................................................................22 How to use Best Practices for Structuring Bundles..............................................................................25 How to use Bundle Inheritance to Override parts of a Bundle .............................................................30 How to Override any Part of a Bundle ...............................................................................................32 How to remove the AcmeDemoBundle ..............................................................................................35 How to expose a Semantic Configuration for a Bundle .......................................................................38 How to simplify configuration of multiple Bundles ............................................................................47 How to use Varnish to speed up my Website .....................................................................................50 How to Master and Create new Environments ...................................................................................55 How to override Symfony's Default Directory Structure......................................................................60 Understanding how the Front Controller, Kernel and Environments work together.............................63 How to Set External Parameters in the Service Container ...................................................................66 How to use PdoSessionHandler to store Sessions in the Database .......................................................69 How to use the Apache Router ..........................................................................................................72 Configuring a web server...................................................................................................................74 How to create a Console Command ..................................................................................................77 How to use the Console ....................................................................................................................81 How to generate URLs and send Emails from the Console..................................................................83 How to enable logging in Console Commands ...................................................................................85 How to customize Error Pages...........................................................................................................90 How to define Controllers as Services ................................................................................................92 How to optimize your development Environment for debugging ........................................................96 How to deploy a Symfony2 application..............................................................................................98 How to handle File Uploads with Doctrine ...................................................................................... 102 How to use Doctrine Extensions: Timestampable, Sluggable, Translatable, etc. ................................ 111 How to Register Event Listeners and Subscribers ............................................................................. 112 How to use Doctrine's DBAL Layer ................................................................................................. 115 How to generate Entities from an Existing Database......................................................................... 117 How to work with Multiple Entity Managers and Connections......................................................... 121 How to Register Custom DQL Functions......................................................................................... 124 How to Define Relationships with Abstract Classes and Interfaces.................................................... 125
PDF brought to you by generated on November 10, 2013
How to provide model classes for several Doctrine implementations................................................. 128 How to implement a simple Registration Form ................................................................................ 131 How to send an Email ..................................................................................................................... 137 How to use Gmail to send Emails .................................................................................................... 140 How to Work with Emails During Development .............................................................................. 141 How to Spool Emails....................................................................................................................... 143 How to test that an Email is sent in a functional Test ....................................................................... 145 How to setup before and after Filters ............................................................................................... 147 How to extend a Class without using Inheritance............................................................................. 151 How to customize a Method Behavior without using Inheritance...................................................... 154 How to customize Form Rendering ................................................................................................. 156 How to use Data Transformers........................................................................................................ 168 How to Dynamically Modify Forms Using Form Events ................................................................... 174 How to Embed a Collection of Forms .............................................................................................. 183 How to Create a Custom Form Field Type....................................................................................... 196 How to Create a Form Type Extension ............................................................................................ 201 How to Reduce Code Duplication with "inherit_data" ..................................................................... 206 How to Unit Test your Forms.......................................................................................................... 209 How to configure Empty Data for a Form Class ............................................................................... 214 How to use the submit() Function to handle Form Submissions ....................................................... 216 How to use the Virtual Form Field Option....................................................................................... 219 How to use Monolog to write Logs.................................................................................................. 220 How to Configure Monolog to Email Errors .................................................................................... 224 How to log Messages to different Files ............................................................................................. 226 How to create a custom Data Collector............................................................................................ 228 How to use Matchers to enable the Profiler Conditionally ................................................................ 231 How to register a new Request Format and Mime Type.................................................................... 233 How to force routes to always use HTTPS or HTTP......................................................................... 235 How to allow a "/" character in a route parameter ............................................................................ 236 How to configure a redirect to another route without a custom controller......................................... 237 How to use HTTP Methods beyond GET and POST in Routes......................................................... 238 How to use Service Container Parameters in your Routes ................................................................. 240 How to create a custom Route Loader ............................................................................................. 241 How to load Security Users from the Database (the Entity Provider) ................................................. 245 How to add "Remember Me" Login Functionality ............................................................................ 256 How to implement your own Voter to blacklist IP Addresses............................................................ 259 How to use Access Control Lists (ACLs).......................................................................................... 262 How to use Advanced ACL Concepts .............................................................................................. 266 How to force HTTPS or HTTP for Different URLs ........................................................................... 270 How to customize your Form Login ................................................................................................ 271 How to secure any Service or Method in your Application................................................................ 274 How to create a custom User Provider ............................................................................................. 278 How to create a custom Authentication Provider ............................................................................. 283 How to change the Default Target Path Behavior ............................................................................. 292 How to use the Serializer ................................................................................................................. 294 How to create an Event Listener ...................................................................................................... 296 How to work with Scopes ............................................................................................................... 299
iv | Contents at a Glance
Contents at a Glance | 4
How to work with Compiler Passes in Bundles ................................................................................ 304 Session Proxy Examples .................................................................................................................. 305 Making the Locale "Sticky" during a User's Session .......................................................................... 307 Configuring the Directory where Sessions Files are Saved ................................................................. 309 Bridge a legacy application with Symfony Sessions ........................................................................... 310 How Symfony2 differs from symfony1 ............................................................................................. 312 How to Inject Variables into all Templates (i.e. Global Variables) ..................................................... 318 How to use and Register namespaced Twig Paths ............................................................................ 320 How to use PHP instead of Twig for Templates ............................................................................... 322 How to write a custom Twig Extension ........................................................................................... 327 How to render a Template without a custom Controller................................................................... 330 How to simulate HTTP Authentication in a Functional Test ............................................................ 332 How to simulate Authentication with a Token in a Functional Test .................................................. 333 How to test the Interaction of several Clients ................................................................................... 335 How to use the Profiler in a Functional Test..................................................................................... 336 How to test code that interacts with the Database ............................................................................ 338 How to test Doctrine Repositories ................................................................................................... 341 How to customize the Bootstrap Process before running Tests.......................................................... 343 How to create a Custom Validation Constraint ................................................................................ 345 How to Create a SOAP Web Service in a Symfony2 Controller ......................................................... 348 How to Create and store a Symfony2 Project in git ........................................................................... 352 How to Create and store a Symfony2 Project in Subversion .............................................................. 356
Contents at a Glance | v
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 both CSS stylesheets and JavaScript files. The philosophy behind adding either is basically the same, but with a slightly different syntax.
You can also include CSS Stylesheets: see Including CSS Stylesheets.
In this example, all of the files in the Resources/public/js/ directory of the AcmeFooBundle will be loaded and served from a different location. The actual rendered tag might simply look like:
Listing 1-3
1 <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 {% stylesheets 'bundles/acme_foo/css/*' filter='cssrewrite' %} 2 <link rel="stylesheet" href="{{ asset_url }}" /> 3 {% endstylesheets %}
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 @AcmeFooBundle/Resources/public/file.js, but that in this example, you referred to the CSS files using their actual, publicly-accessible path: bundles/acme_foo/css. You can use either, except that there is a known issue that causes the cssrewrite filter to fail when using the @AcmeFooBundle syntax for CSS Stylesheets.
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-5
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:
Listing 1-6
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 front-end optimization). Other filters can compile JavaScript file from CoffeeScript files 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 JavaScript YUI Compressor the following config should be added:
Listing 1-7
Now, to actually use the filter on a group of JavaScript files, add it into your template:
Listing 1-8
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 JavaScripts and Stylesheets with YUI Compressor.
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 assets_version configuration option.
1 <script src="/app_dev.php/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 app in the prod environment (and therefore, each time you deploy), you should run the following task:
Listing 1-11
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.
Next, since Symfony is no longer generating these assets for you, you'll need to dump them manually. To do so, run the following:
Listing 1-13
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 passing the --watch option, the command will automatically regenerate assets as they change:
Listing 1-14
Since running this command in the dev environment may generate a bunch of files, it's usually a good idea to point your generated assets files to some isolated directory (e.g. /js/compiled), to keep things organized:
Listing 1-15
Chapter 2
Install UglifyJs
UglifyJs is available as an Node.js3 npm module and can be installed using npm. First, you need to install node.js4. Afterwards you can install UglifyJs using npm:
Listing 2-1
This command will install UglifyJs globally and you may need to run it as a root user.
It's also possible to install UglifyJs inside your project only. To do this, install it without the -g option and specify the path where to put the module:
Listing 2-2
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.
Depending on your installation method, you should either be able to execute the uglifyjs executable globally, or execute the physical file that lives in the node_modules directory:
Listing 2-3
1 # app/config/config.yml 2 assetic: 3 filters: 4 uglifyjs2: 5 # the path to the uglifyjs executable 6 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, you can use the following command:
Listing 2-5
1 $ 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.
5. http://package.json.nodejitsu.com/
The above example assumes that you have a bundle called AcmeFooBundle 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 uglifyjs2 filter to the asset tags above, you should now see minified JavaScripts coming over the wire much faster.
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 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 uglifyjs2 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.
To use the filter for your css files, add the filter to the Assetic stylesheets helper:
Listing 2-10
1 {% stylesheets '@AcmeFooBundle/Resources/public/css/*' filter='uglifycss' %} 2 <link rel="stylesheet" href="{{ asset_url }}" /> 3 {% endstylesheets %}
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 3
7 8
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.
The above example assumes that you have a bundle called AcmeFooBundle 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 3-3
1 {% stylesheets '@AcmeFooBundle/Resources/public/css/*' filter='yui_css' %} 2 <link rel="stylesheet" type="text/css" media="screen" href="{{ asset_url }}" /> 3 {% endstylesheets %}
Instead of adding the filter to the asset tags, you can also globally enable it by adding the applyto 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 4
Using Jpegoptim
Jpegoptim1 is a utility for optimizing JPEG files. To use it with Assetic, add the following to the Assetic config:
Listing 4-1
Notice that to use jpegoptim, you must have it already installed on your system. The bin option points to the location of the compiled binary.
1 {% image '@AcmeFooBundle/Resources/public/images/example.jpg' 2 filter='jpegoptim' output='/images/example.jpg' %} 3 <img src="{{ asset_url }}" alt="Example"/> 4 {% endimage %}
1. http://www.kokkonen.net/tjko/projects.html
Chapter 4: How to Use Assetic For Image Optimization with Twig Functions | 17
You can specify the output directory in the config in the following way:
Listing 4-7
Chapter 4: How to Use Assetic For Image Optimization with Twig Functions | 18
7 8
Chapter 4: How to Use Assetic For Image Optimization with Twig Functions | 19
Chapter 5
1 # app/config/config.yml 2 assetic: 3 filters: 4 coffee: 5 bin: /usr/bin/coffee 6 node: /usr/bin/node 7 node_paths: [ /usr/lib/node_modules/ ]
This is all that's needed to compile this CoffeeScript file and server it as the compiled JavaScript.
Listing 5-3
1 {% javascripts '@AcmeFooBundle/Resources/public/js/example.coffee' 2 '@AcmeFooBundle/Resources/public/js/another.coffee' 3 filter='coffee' %} 4 <script src="{{ asset_url }}" type="text/javascript"></script> 5 {% endjavascripts %}
Both the files will now be served up as a single file compiled into regular JavaScript.
# app/config/config.yml assetic: filters: coffee: bin: /usr/bin/coffee node: /usr/bin/node node_paths: [ /usr/lib/node_modules/ ] apply_to: "\.coffee$"
With this, 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 5-5
1 {% javascripts '@AcmeFooBundle/Resources/public/js/example.coffee' 2 '@AcmeFooBundle/Resources/public/js/another.coffee' 3 '@AcmeFooBundle/Resources/public/js/regular.js' %} 4 <script src="{{ asset_url }}" type="text/javascript"></script> 5 {% endjavascripts %}
Chapter 6
Now that you have the package name, you should determine the version you want to use. Usually different versions of a bundle correspond to a particular version of Symfony. This information should be in the README file. If it isn't, you can use the version you want. If you choose an incompatible version, Composer will throw dependency errors when you try to install. If this happens, you can try a different version. In the case of the FOSUserBundle, the README file has a caution that version 1.2.0 must be used for Symfony 2.0 and 1.3+ for Symfony 2.1+. Packagist displays example require statements for all existing versions of a package. The current development version of FOSUserBundle is "friendsofsymfony/ user-bundle": "2.0.*@dev".
Now you can add the bundle to your composer.json file and update the dependencies. You can do this manually: 1. Add it to the composer.json file:
Listing 6-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// ...
} }
For instance, in order to look the reference of the assetic config you can use this:
Listing 6-6
or this:
Listing 6-7
1 assetic: 2 debug: 3 use_controller: 4 enabled: 5 profiler: 6 read_from: 7 write_to: 8 java: 9 node: 10 node_paths: 11 # ...
Other Setup
At this point, check the README file of your brand new bundle to see what do to next.
Chapter 7
Bundle Name
A bundle is also a PHP namespace. The namespace must follow the technical interoperability standards1 for PHP 5.3 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: Use only alphanumeric characters and underscores; Use a CamelCased name; Use a descriptive and short name (no more than 2 words); Prefix the name with the concatenation of the vendor (and optionally the category namespaces); Suffix the name with Bundle. Here are some valid bundle namespaces and class names: Namespace Acme\Bundle\BlogBundle Bundle Class Name AcmeBlogBundle
1. http://symfony.com/PSR0
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).
Symfony2 core Bundles do not prefix the Bundle class with Symfony and always add a Bundle subnamespace; for example: FrameworkBundle2.
Each bundle has an alias, which is the lower-cased short version of the bundle name using underscores (acme_hello for AcmeHelloBundle, or acme_social_blog for Acme\Social\BlogBundle for instance). This alias is used to enforce uniqueness within a bundle (see below for some usage examples).
Directory Structure
The basic directory structure of a HelloBundle bundle must read as follows:
Listing 7-1
1 XXX/... 2 HelloBundle/ 3 HelloBundle.php 4 Controller/ 5 Resources/ 6 meta/ 7 LICENSE 8 config/ 9 doc/ 10 index.rst 11 translations/ 12 views/ 13 public/ 14 Tests/
The XXX directory(ies) reflects the namespace structure of the bundle. The following files are mandatory: HelloBundle.php; Resources/meta/LICENSE: The full license for the code; Resources/doc/index.rst: The root file for the Bundle documentation.
These conventions ensure that automated tools can rely on this default structure to work.
The depth of sub-directories should be kept to the minimal for most used classes and files (2 levels at a maximum). More levels can be defined for non-strategic, less-used files. 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:
2. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/FrameworkBundle.html
Type Commands Controllers Event Listeners Configuration Web Resources Translation files Templates Unit and Functional Tests
Service Container Extensions DependencyInjection/ EventListener/ Resources/config/ Resources/public/ Resources/translations/ Resources/views/ Tests/
When building a reusable bundle, model classes should be placed in the Model namespace. 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 hierarchy. For instance, a HelloController controller is stored in Bundle/HelloBundle/Controller/HelloController.php and the fully qualified class name is Bundle\HelloBundle\Controller\HelloController. All classes and files must follow the Symfony2 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. Exceptions 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 Symfony2 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: 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.
Controllers
As a best practice, controllers in a bundle that's meant to be distributed to others must not extend the Controller3 base class. They can implement ContainerAwareInterface4 or extend ContainerAware5 instead.
If you have a look at Controller6 methods, you will see that they are only nice shortcuts to ease the learning curve.
Routing
If the bundle provides routes, they must be prefixed with the bundle alias. For an AcmeBlogBundle for instance, all 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 (bundle.hello). A bundle must not override existing messages from another bundle.
Configuration
To provide more flexibility, a bundle can provide configurable settings by using the Symfony2 built-in mechanisms. For simple configuration settings, rely on the default parameters entry of the Symfony2 configuration. Symfony2 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_hello.email.from). The end user can provide values in any configuration file:
Listing 7-2
1 $container->getParameter('acme_hello.email.from');
Even if this mechanism is simple enough, you are highly encouraged to use the semantic configuration described in the cookbook.
If you are defining services, they should also be prefixed with the bundle alias.
Chapter 8
1 2 3 4 5 6 7 8 9 10 11 12
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
Suppose you want to 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:
Listing 8-2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Depending on how severely you need to change the behavior, you might call parent::registerAction() or completely replace its logic with your own.
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.
Translation and validation files do not work in the same way as described above. Read "Translations" if you want to learn how to override translations and see "Validation metadata" for tricks to override the validation.
Chapter 9
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 Symfony2. 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 thirdparty bundle's routing, simply copying 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.
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 you need to modify something beyond just the class name, you should use a compiler pass:
Listing 9-2
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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.:
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#overrides
Listing 9-3
1 $builder->add('name', 'custom_type');
rather than:
Listing 9-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 9-5
1 # src/Acme/UserBundle/Resources/config/validation.yml 2 Fos\UserBundle\Model\User: 3 properties: 4 plainPassword: 5 - NotBlank: 6 groups: [AcmeValidation] 7 - Length: 8 min: 6 9 minMessage: fos_user.password.short 10 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 mean 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. The file that always wins is the one that is placed in app/Resources/translations, as those files are always loaded last.
Chapter 10
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(); // ... } } }
1 echo $this->container->get('kernel')->getBundle('AcmeDemoBundle')->getPath();
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.
If one bundle relies on another, in most it means that it uses some services from the bundle. Searching for a acme_demo string may help you spot them.
1. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Bundle/Bundle.html#getPath()
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 11
When you create a bundle, you have two choices on how to handle configuration: 1. Normal Service Configuration (easy): You can specify your services in a configuration file (e.g. services.yml) that lives in your bundle and then import it from your main application configuration. This is really easy, quick and totally effective. If you make use of parameters, then you still have the flexibility to customize your bundle from your application configuration. See "Importing Configuration with imports" for more details. 2. Exposing Semantic Configuration (advanced): This is the way configuration is done with the core bundles (as described above). The basic idea is that, instead of having the user override individual parameters, you let the user configure just a few, specifically created options. As the bundle developer, you then parse through that configuration and load services inside an "Extension" class. With this method, you won't need to import any configuration resources from your main application configuration: the Extension class can handle all of this.
The second option - which you'll learn about in this article - is much more flexible, but also requires more time to setup. If you're wondering which method you should use, it's probably a good idea to start with method #1, and then change to #2 later if you need to. If you plan to distribute your bundle, the second option is recommended. The second method has several specific advantages: Much more powerful than simply defining parameters: a specific option value might trigger the creation of many service definitions; Ability to have configuration hierarchy Smart merging when several configuration files (e.g. config_dev.yml and config.yml) override each other's configuration; Configuration validation (if you use a Configuration Class); IDE auto-completion when you create an XSD and developers use XML.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
The getXsdValidationBasePath and getNamespace methods are only required if the bundle provides optional XSD's for the configuration.
The presence of the previous class means that you can now define an acme_hello configuration namespace in any configuration file. The namespace acme_hello is constructed from the extension's class name by removing the word Extension and then lowercasing and underscoring the rest of the name. In other words, AcmeHelloExtension becomes acme_hello. You can begin specifying configuration under this namespace immediately:
Listing 11-3
1 # app/config/config.yml 2 acme_hello: ~
If you follow the naming conventions laid out above, then the load() method of your extension code is always called as long as your bundle is registered in the Kernel. In other words, even if the user does not provide any configuration (i.e. the acme_hello entry doesn't even appear), the load() method will be called and passed an empty $configs array. You can still provide some sensible defaults for your bundle if you want.
The array passed to your load() method will look like this:
Listing 11-5
Notice that this is an array of arrays, not just a single flat array of the configuration values. This is intentional. For example, if acme_hello appears in another configuration file - say config_dev.yml with different values beneath it, then the incoming array might look like this:
Listing 11-6
7 8 9 10 )
The order of the two arrays depends on which one is set first. It's your job, then, to decide how these configurations should be merged together. You might, for example, have later values override previous values or somehow merge them together. Later, in the Configuration Class section, you'll learn of a truly robust way to handle this. But for now, you might just merge them manually:
Listing 11-7
1 public function load(array $configs, ContainerBuilder $container) 2 { 3 $config = array(); 4 foreach ($configs as $subConfig) { 5 $config = array_merge($config, $subConfig); 6 } 7 8 // ... now use the flat $config array 9 }
Make sure the above merging technique makes sense for your bundle. This is just an example, and you should be careful to not use it blindly.
1 2 3 4 5 6 7 8 9 10 11 12 13
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\Config\FileLocator; public function load(array $configs, ContainerBuilder $container) { // ... prepare your $config variable $loader = new XmlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.xml'); }
You might even do this conditionally, based on one of the configuration values. For example, suppose you only want to load a set of services if an enabled option is passed and set to true:
Listing 11-9
1 public function load(array $configs, ContainerBuilder $container) 2 { 3 // ... prepare your $config variable 4 5 $loader = new XmlFileLoader( 6 $container, 7 new FileLocator(__DIR__.'/../Resources/config') 8 ); 9 10 if (isset($config['enabled']) && $config['enabled']) { 11 $loader->load('services.xml'); 12 } 13 }
1 <!-- src/Acme/HelloBundle/Resources/config/services.xml --> 2 <container xmlns="http://symfony.com/schema/dic/services" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/ 5 dic/services/services-1.0.xsd"> 6 7 <parameters> 8 <parameter key="acme_hello.my_service_type" /> 9 </parameters> 10 11 <services> 12 <service id="acme_hello.my_service" class="Acme\HelloBundle\MyService"> 13 <argument>%acme_hello.my_service_type%</argument> 14 </service> 15 </services> </container>
But why would you define an empty parameter and then pass it to your service? The answer is that you'll set this parameter in your extension class, based on the incoming configuration values. Suppose, for example, that you want to allow the user to define this type option under a key called my_type. Add the following to the load() method to do this:
Listing 11-11
1 public function load(array $configs, ContainerBuilder $container) 2 { 3 // ... prepare your $config variable 4 5 $loader = new XmlFileLoader( 6 $container, 7 new FileLocator(__DIR__.'/../Resources/config') 8 ); 9 $loader->load('services.xml');
10 11 12 13 14 15 16 17 18 19 20 21 }
if (!isset($config['my_type'])) { throw new \InvalidArgumentException( 'The "my_type" option must be set' ); } $container->setParameter( 'acme_hello.my_service_type', $config['my_type'] );
Now, the user can effectively configure the service by specifying the my_type configuration value:
Listing 11-12
Global Parameters
When you're configuring the container, be aware that you have the following global parameters available to use: kernel.name kernel.environment kernel.debug kernel.root_dir kernel.cache_dir kernel.logs_dir kernel.bundles kernel.charset
All parameter and service names starting with a _ are reserved for the framework, and new ones must not be defined by bundles.
To take advantage of this system, you'll create a Configuration class and build a tree that defines your configuration in that class:
Listing 11-13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
This is a very simple example, but you can now use this class in your load() method to merge your configuration and force validation. If any options other than my_type are passed, the user will be notified with an exception that an unsupported option was passed:
Listing 11-14
1 public function load(array $configs, ContainerBuilder $container) 2 { 3 $configuration = new Configuration(); 4 5 $config = $this->processConfiguration($configuration, $configs); 6 7 // ... 8 }
The processConfiguration() method uses the configuration tree you've defined in the Configuration class to validate, normalize and merge all of the configuration arrays together. The Configuration class can be much more complicated than shown here, supporting array nodes, "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 of the core Configuration classes, such as the one from the FrameworkBundle Configuration1 or the TwigBundle Configuration2.
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
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
This text appears as yaml comments in the output of the config:dump-reference command.
Extension Conventions
When creating an extension, follow these simple conventions: The extension must be stored in the DependencyInjection sub-namespace; The extension must be named after the bundle name and suffixed with Extension (AcmeHelloExtension for AcmeHelloBundle); The extension should provide an XSD schema. If you follow these simple conventions, your extensions will be registered automatically by Symfony2. If not, override the Bundle::build()4 method in your bundle:
Listing 11-16
3. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/DependencyInjection/Extension.html#getConfiguration() 4. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Bundle/Bundle.html#build()
1 2 3 4 5 6 7 8 9 10 11 12 13
// register extensions that do not follow the conventions manually $container->registerExtension(new UnconventionalExtensionClass());
} }
In this case, the extension class must also implement a getAlias() method and return a unique alias named after the bundle (e.g. acme_hello). This is required because the class name doesn't follow the standards by ending in Extension. Additionally, the load() method of your extension will only be called if the user specifies the acme_hello alias in at least one configuration file. Once again, this is because the Extension class doesn't follow the standards set out above, so nothing happens automatically.
Chapter 12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1. http://api.symfony.com/2.3/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 12-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
public function prepend(ContainerBuilder $container) { // get all Bundles $bundles = $container->getParameter('kernel.bundles'); // determine if AcmeGoodbyeBundle is registered if (!isset($bundles['AcmeGoodbyeBundle'])) { // disable AcmeGoodbyeBundle in Bundles $config = array('use_acme_goodbye' => false); foreach ($container->getExtensions() as $name => $extension) { switch ($name) { case 'acme_something': case 'acme_other': // set use_acme_goodbye to false in the config of acme_something and acme_other // note that if the user manually configured use_acme_goodbye to true in the // app/config/config.yml then the setting would in the end be true and not false $container->prependExtensionConfig($name, $config); break; } } }
// process the configuration of AcmeHelloExtension $configs = $container->getExtensionConfig($this->getAlias()); // use the Configuration class to generate a config array with the settings ``acme_hello`` $config = $this->processConfiguration(new Configuration(), $configs); // check if entity_manager_name is set in the ``acme_hello`` configuration if (isset($config['entity_manager_name'])) { // prepend the acme_something settings with the entity_manager_name $config = array('entity_manager_name' => $config['entity_manager_name']); $container->prependExtensionConfig('acme_something', $config); }
}
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 12-3
1 # app/config/config.yml 2
3 acme_something: 4 # ... 5 use_acme_goodbye: false 6 entity_manager_name: non_default 7 8 acme_other: 9 # ... 10 use_acme_goodbye: false
Chapter 13
Configuration
As seen previously, Symfony2 is smart enough to detect whether it talks to a reverse proxy that understands ESI or not. It works out of the box when you use the Symfony2 reverse proxy, but you need a special configuration to make it work with Varnish. Thankfully, Symfony2 relies on yet another standard written by Akama (Edge Architecture2), so the configuration tips in this chapter can be useful even if you don't use Symfony2.
Varnish only supports the src attribute for ESI tags (onerror and alt attributes are ignored).
First, configure Varnish so that it advertises its ESI support by adding a Surrogate-Capability header to requests forwarded to the backend application:
Listing 13-1
1 sub vcl_recv { 2 // Add a Surrogate-Capability header to announce ESI support. 3 set req.http.Surrogate-Capability = "abc=ESI/1.0"; 4 }
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 Symfony2 adds automatically:
Listing 13-2
1. https://www.varnish-cache.org 2. http://www.w3.org/TR/edge-arch
1 sub vcl_fetch { 2 /* 3 Check for ESI acknowledgement 4 and remove Surrogate-Control header 5 */ 6 if (beresp.http.Surrogate-Control ~ "ESI/1.0") { 7 unset beresp.http.Surrogate-Control; 8 9 // For Varnish >= 3.0 10 set beresp.do_esi = true; 11 // For Varnish < 3.0 12 // esi; 13 } 14 }
Compression with ESI was not supported in Varnish until version 3.0 (read GZIP and Varnish3). If you're not using Varnish 3.0, put a web server in front of Varnish to perform the compression.
Cache Invalidation
You should never need to invalidate cached data because invalidation is already taken into account natively in the HTTP cache models (see Cache Invalidation). Still, Varnish can be configured to accept a special HTTP PURGE method that will invalidate the cache for a given resource:
Listing 13-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
/* Connect to the backend server on the local machine on port 8080 */ backend default { .host = "127.0.0.1"; .port = "8080"; } sub vcl_recv { /* Varnish default behaviour doesn't support PURGE. Match the PURGE request and immediately do a cache lookup, otherwise Varnish will directly pipe the request to the backend and bypass the cache */ if (req.request == "PURGE") { return(lookup); } } sub vcl_hit { // Match PURGE request if (req.request == "PURGE") { // Force object expiration for Varnish < 3.0 set obj.ttl = 0s;
3. https://www.varnish-cache.org/docs/3.0/phk/gzip.html
27 28 29 30 31 } 32 33 sub 34 35 36 37 38 39 40 41 }
// Do an actual purge for Varnish >= 3.0 // purge; error 200 "Purged"; } vcl_miss { /* Match the PURGE request and indicate the request wasn't stored in cache. */ if (req.request == "PURGE") { error 404 "Not purged"; }
You must protect the PURGE HTTP method somehow to avoid random people purging your cached data. You can do this by setting up an access list:
Listing 13-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 40 41 42 43 44 45 46
/* Connect to the backend server on the local machine on port 8080 */ backend default { .host = "127.0.0.1"; .port = "8080"; } // Acl's can contain IP's, subnets and hostnames acl purge { "localhost"; "192.168.55.0"/24; } sub vcl_recv { // Match PURGE request to avoid cache bypassing if (req.request == "PURGE") { // Match client IP to the acl if (!client.ip ~ purge) { // Deny access error 405 "Not allowed."; } // Perform a cache lookup return(lookup); } } sub vcl_hit { // Match PURGE request if (req.request == "PURGE") { // Force object expiration for Varnish < 3.0 set obj.ttl = 0s; // Do an actual purge for Varnish >= 3.0 // purge; error 200 "Purged"; } } sub vcl_miss { // Match PURGE request if (req.request == "PURGE") { // Indicate that the object isn't stored in cache error 404 "Not purged"; } }
If this header weren't set properly, Symfony may append 8080 when generating absolute URLs:
Listing 13-5
1 sub vcl_recv { 2 if (req.http.X-Forwarded-Proto == "https" ) { 3 set req.http.X-Forwarded-Port = "443"; 4 } else { 5 set req.http.X-Forwarded-Port = "80"; 6 } 7 }
Remember to configure framework.trusted_proxies in the Symfony configuration so that Varnish is seen as a trusted proxy and the X-Forwarded- headers are used.
Chapter 14
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(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
As you can see, when Symfony2 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 "dev" configuration file, you can see how this is accomplished easily and transparently:
Listing 14-2
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 default value in the dev configuration file:
Listing 14-3
1 http://localhost/app.php 2 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 Symfony2.
If you open up one of these files, you'll quickly see that the environment used by each is explicitly set:
Listing 14-5
1 2 3 4 5 6 7 8 9
<?php require_once __DIR__.'/../app/bootstrap_cache.php'; require_once __DIR__.'/../app/AppCache.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppCache(new AppKernel('prod', false)); $kernel->handle(Request::createFromGlobals())->send();
As you can see, the prod key specifies that this environment will run in the prod environment. A Symfony2 application can be executed in any environment by using this code and changing the environment string.
PDF brought to you by generated on November 10, 2013 Chapter 14: How to Master and Create new Environments | 56
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 key on line 8 of the front controller above. This specifies whether or not the application should run in "debug mode". Regardless of the environment, a Symfony2 application can be run with debug mode set to true or false. This affects many things in the application, such as whether or not the 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 14-6
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.
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.
1. http://api.symfony.com/2.3/Symfony/Component/Debug/Debug.html#enable()
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 14-8
1 2 3 4 5 6 7 8 9
<?php require_once __DIR__.'/../app/bootstrap.php'; require_once __DIR__.'/../app/AppKernel.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('benchmark', false); $kernel->handle(Request::createFromGlobals())->send();
1 http://localhost/app_benchmark.php
Some environments, like the dev environment, are never meant to be accessed on any deployed server by the general 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:
1 if (!in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) { 2 die('You are not allowed to access this file. Check 3 '.basename(__FILE__).' for more information.'); }
Listing 14-10
1 app/cache/dev 2 app/cache/prod
- cache directory for the *dev* environment - cache directory for the *prod* environment
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;
PDF brought to you by generated on November 10, 2013 Chapter 14: How to Master and Create new Environments | 58
Going Further
Read the article on How to Set External Parameters in the Service Container.
Chapter 15
1 2 3 4 5 6 7 8 9 10 11 12
app/ cache/ config/ logs/ ... src/ ... vendor/ ... web/ app.php ...
1 2 3 4 5 6 7 8
9 10 11 12 }
{ 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 behaviour may happen. Each environment generates its own cached config files, and so each needs its own directory to store those cache files.
1 2 3 4 5 6 7 8 9 10 11 12
Since Symfony 2.1 (in which Composer is introduced), you also need to change the extra.symfony-webdir option in the composer.json file:
Listing 15-5
} }
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 this, so it can use the correct web directory:
Listing 15-6
Now you just need to dump the assets again and your application should work:
Listing 15-7
Chapter 16
Understanding how the Front Controller, Kernel and Environments work together
The section How to Master and Create new Environments explained the basics on how Symfony uses environments to run your application with different configuration settings. This section will explain a bit more in-depth what happens when your application is bootstrapped. To hook into this process, you need to understand three parts that work together: The Front Controller The Kernel Class The Environments
Usually, you will not need to define your own front controller or AppKernel class as the Symfony2 Standard Edition1 provides sensible default implementations. This documentation section is provided to explain what is going on behind the scenes.
Chapter 16: Understanding how the Front Controller, Kernel and Environments work together | 63
Because every request is routed through it, the front controller can be used to perform global initializations prior to setting up the kernel or to decorate6 the kernel with additional features. Examples include: Configuring the autoloader or adding additional autoloading mechanisms; Adding HTTP level caching by wrapping the kernel with an instance of AppCache; Enabling (or skipping) the ClassCache Enabling the Debug Component.
1 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 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. http://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.3/Symfony/Component/HttpKernel/Kernel.html 10. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/HttpKernelInterface.html#handle() 11. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelInterface.html 12. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Kernel.html 13. http://en.wikipedia.org/wiki/Template_method_pattern 14. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelInterface.html#registerBundles() 15. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelInterface.html#registerContainerConfiguration()
Chapter 16: Understanding how the Front Controller, Kernel and Environments work together | 64
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 Symfony2 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
We just mentioned another method the AppKernel has to implement registerContainerConfiguration()19. This method is responsible for loading the application's configuration from the right environment. Environments have been covered extensively in the previous chapter, and you probably remember that the Standard Edition comes with three of them - dev, prod and test. More technically, these names are nothing more than strings passed from the front controller to the AppKernel's constructor. This name can then be used in the registerContainerConfiguration()20 method to decide which configuration files to load. The Standard Edition's AppKernel21 class implements this method by simply loading the app/config/ config_*environment*.yml file. You are, of course, free to implement this method differently if you need a more sophisticated way of loading your configuration.
16. https://github.com/symfony/symfony-standard/blob/master/app/AppKernel.php 17. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Kernel.html#__construct() 18. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Kernel.html#getEnvironment() 19. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelInterface.html#registerContainerConfiguration() 20. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelInterface.html#registerContainerConfiguration() 21. https://github.com/symfony/symfony-standard/blob/master/app/AppKernel.php
Chapter 16: Understanding how the Front Controller, Kernel and Environments work together | 65
Chapter 17
Environment Variables
Symfony will grab any environment variable prefixed with SYMFONY__ and set it as a parameter in the service container. 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 17-1
1 <VirtualHost *:80> 2 ServerName Symfony2 3 DocumentRoot "/path/to/symfony_2_app/web" 4 DirectoryIndex index.php index.html 5 SetEnv SYMFONY__DATABASE__USER user 6 SetEnv SYMFONY__DATABASE__PASSWORD secret 7 8 <Directory "/path/to/symfony_2_app/web"> 9 AllowOverride All 10 Allow from All 11 </Directory> 12 </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 17-2
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 17-3
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 17-4
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 nonstandard format. The example below includes a Drupal database's configuration in the Symfony service container.
Listing 17-5
1. http://httpd.apache.org/docs/current/env.html
Chapter 18
Listing 18-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.html
17 arguments: 18 dsn: "mysql:dbname=mydatabase" 19 user: myuser 20 password: mypassword 21 calls: 22 - [setAttribute, [3, 2]] # \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION 23 24 session.handler.pdo: 25 class: 26 Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler arguments: ["@pdo", "%pdo.db_options%"]
db_table: The name of the session table in your database db_id_col: The name of the id column in your session table (VARCHAR(255) or larger) db_data_col: The name of the value column in your session table (TEXT or CLOB) db_time_col: The name of the time column in your session table (INTEGER)
1 CREATE TABLE `session` ( 2 `session_id` varchar(255) NOT NULL, 3 `session_value` text NOT NULL, 4 `session_time` int(11) NOT NULL, 5 PRIMARY KEY (`session_id`) 6 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
PostgreSQL
For PostgreSQL, the statement should look like this:
Listing 18-4
1 CREATE TABLE session ( 2 session_id character varying(255) NOT NULL, 3 session_value text NOT NULL, 4 session_time integer NOT NULL, 5 CONSTRAINT session_pkey PRIMARY KEY (session_id) 6 );
1 CREATE TABLE [dbo].[session]( 2 [session_id] [nvarchar](255) NOT NULL, 3 [session_value] [ntext] NOT NULL, 4 [session_time] [int] NOT NULL, 5 PRIMARY KEY CLUSTERED( 6 [session_id] ASC 7 ) WITH ( 8 PAD_INDEX = OFF, 9 STATISTICS_NORECOMPUTE = OFF, 10 IGNORE_DUP_KEY = OFF, 11 ALLOW_ROW_LOCKS = ON, 12 ALLOW_PAGE_LOCKS = ON 13 ) ON [PRIMARY] 14 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Chapter 19
Note that ApacheUrlMatcher1 extends UrlMatcher2 so even if you don't regenerate the url_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.3/Symfony/Component/Routing/Matcher/ApacheUrlMatcher.html 2. http://api.symfony.com/2.3/Symfony/Component/Routing/Matcher/UrlMatcher.html
1 2 3 4 5 6 7
# skip "real" requests RewriteCond %{REQUEST_FILENAME} -f RewriteRule .* - [QSA,L] # hello RewriteCond %{REQUEST_URI} ^/hello/([^/]+?)$ RewriteRule .* app.php [QSA,L,E=_ROUTING__route:hello,E=_ROUTING_name:%1,E=_ROUTING__controller:AcmeDemoBundle\:Demo\:hello]
You can now rewrite web/.htaccess to use the new rules, so with this example it should look like this:
Listing 19-5
1 <IfModule mod_rewrite.c> 2 RewriteEngine On 3 4 # skip "real" requests 5 RewriteCond %{REQUEST_FILENAME} -f 6 RewriteRule .* - [QSA,L] 7 8 # hello 9 RewriteCond %{REQUEST_URI} ^/hello/([^/]+?)$ 10 RewriteRule .* app.php 11 [QSA,L,E=_ROUTING__route:hello,E=_ROUTING_name:%1,E=_ROUTING__controller:AcmeDemoBundle\:Demo\:hello] </IfModule>
Procedure above should be done each time you add/change a route if you want to take full advantage of this setup
That's it! You're now all set to use Apache Route rules.
Additional tweaks
To save a little bit of processing time, change occurrences of Request to ApacheRequest in web/app.php:
Listing 19-6
1 2 3 4 5 6 7 8 9 10 11 12
// 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(); // $kernel = new AppCache($kernel); $kernel->handle(ApacheRequest::createFromGlobals())->send();
Chapter 20
Apache2
For advanced Apache configuration options, see the official Apache1 documentation. The minimum basics to get your application running under Apache2 are:
Listing 20-1
1 <VirtualHost *:80> 2 ServerName domain.tld 3 ServerAlias www.domain.tld 4 5 DocumentRoot /var/www/project/web 6 <Directory /var/www/project/web> 7 # enable the .htaccess rewrites 8 AllowOverride All 9 Order allow,deny 10 Allow from All 11 </Directory> 12 13 ErrorLog /var/log/apache2/project_error.log 14 CustomLog /var/log/apache2/project_access.log combined 15 </VirtualHost>
For performance reasons, you will probably want to set AllowOverride None and implement the rewrite rules in the web/.htaccess into the virtualhost config.
1. http://httpd.apache.org/docs/current/mod/core.html#documentroot
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 20-2
1 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
In Apache 2.4, Order allow,deny has been replaced by Require all granted, and hence you need to modify your Directory permission settings as follows:
1 <Directory /var/www/project/web> 2 # enable the .htaccess rewrites 3 AllowOverride All 4 Require all granted 5 </Directory>
Listing 20-3
Nginx
For advanced Nginx configuration options, see the official Nginx2 documentation. The minimum basics to get your application running under Nginx are:
Listing 20-4
1 server { 2 server_name domain.tld www.domain.tld; 3 root /var/www/project/web; 4 5 location / { 6 # try to serve file directly, fallback to rewrite 7 try_files $uri @rewriteapp; 8 } 9 10 location @rewriteapp { 11 # rewrite all to app.php 12 rewrite ^(.*)$ /app.php/$1 last; 13 } 14 15 location ~ ^/(app|app_dev|config)\.php(/|$) { 16 fastcgi_pass unix:/var/run/php5-fpm.sock; 17 fastcgi_split_path_info ^(.+\.php)(/.*)$; 18 include fastcgi_params; 19 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 20 fastcgi_param HTTPS off; 21 } 22 23 error_log /var/log/nginx/project_error.log; 24 access_log /var/log/nginx/project_access.log; 25 }
Depending on your PHP-FPM config, the fastcgi_pass can also be fastcgi_pass 127.0.0.1:9000.
2. http://wiki.nginx.org/Symfony
This executes only app.php, app_dev.php and config.php in the web directory. All other files will be served as text. You must also make sure that if you do deploy app_dev.php or config.php that these files are secured and not available to any outside user (the IP checking code at the top of each file does this by default). 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.
Chapter 21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
class GreetCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('demo:greet') ->setDescription('Greet someone') ->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?') ->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters') ; } protected function execute(InputInterface $input, OutputInterface $output)
24 25 26 27 28 29 30 31 32 33 34 35 36 37 }
{ $name = $input->getArgument('name'); if ($name) { $text = 'Hello '.$name; } else { $text = 'Hello'; } if ($input->getOption('yell')) { $text = strtoupper($text); } $output->writeln($text); }
1 protected function execute(InputInterface $input, OutputInterface $output) 2 { 3 $name = $input->getArgument('name'); 4 $translator = $this->getContainer()->get('translator'); 5 if ($name) { 6 $output->writeln($translator->trans('Hello %name%!', array('%name%' => $name))); 7 } else { 8 $output->writeln($translator->trans('Hello!')); 9 } 10 }
Testing Commands
When testing commands used as part Symfony\Bundle\FrameworkBundle\Console\Application3 Symfony\Component\Console\Application4:
Listing 21-4
of should
the be
full used
framework instead of
5 class ListCommandTest extends \PHPUnit_Framework_TestCase 6 { 7 public function testExecute() 8 { 9 // mock the Kernel or create one depending on your needs 10 $application = new Application($kernel); 11 $application->add(new GreetCommand()); 12 13 $command = $application->find('demo:greet'); 14 $commandTester = new CommandTester($command); 15 $commandTester->execute( 16 array( 17 'command' => $command->getName(), 18 'name' => 'Fabien', 19 '--yell' => true, 20 ) 21 ); 22 23 $this->assertRegExp('/.../', $commandTester->getDisplay()); 24 25 // ... 26 } 27 }
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 WebTestCase5:
Listing 21-5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
class ListCommandTest extends WebTestCase { public function testExecute() { $kernel = $this->createKernel(); $kernel->boot(); $application = new Application($kernel); $application->add(new GreetCommand()); $command = $application->find('demo:greet'); $commandTester = new CommandTester($command); $commandTester->execute( array( 'command' => $command->getName(), 'name' => 'Fabien', '--yell' => true, )
5. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.html
24 25 26 27 28 29 30 }
); $this->assertRegExp('/.../', $commandTester->getDisplay());
// ...
}
Chapter 22
or the equivalent:
Listing 22-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 22-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 22-4
You can now just run commands with the command name:
Listing 22-5
When using the shell you can choose to run each command in a separate process:
PDF brought to you by generated on November 10, 2013 Chapter 22: How to use the Console | 81
Listing 22-6
When you do this, the output will not be colorized and interactivity is not supported so you will need to pass all command params 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 23
Chapter 23: How to generate URLs and send Emails from the Console | 83
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// src/Acme/DemoBundle/Command/DemoCommand.php // ... class DemoCommand extends ContainerAwareCommand { protected function execute(InputInterface $input, OutputInterface $output) { $context = $this->getContainer()->get('router')->getContext(); $context->setHost('example.com'); $context->setScheme('https'); $context->setBaseUrl('my/path'); // ... your code here
} }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Another option is to create an environment which is only used by console commands and uses a different spooling method.
Taking care of the spooling is only needed when memory spooling is used. If you are using file spooling (or no spooling at all), there is no need to flush the queue manually within the command.
Chapter 23: How to generate URLs and send Emails from the Console | 84
Chapter 24
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.html
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 }
protected function execute(InputInterface $input, OutputInterface $output) { /** @var $logger LoggerInterface */ $logger = $this->getContainer()->get('logger'); $name = $input->getArgument('name'); if ($name) { $text = 'Hello '.$name; } else { $text = 'Hello'; } if ($input->getOption('yell')) { $text = strtoupper($text); $logger->warn('Yelled: '.$text); } else { $logger->info('Greeted: '.$text); } $output->writeln($text); }
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.
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 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
use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Input\ArgvInput; class Application extends BaseApplication { private $originalAutoExit; public function __construct(KernelInterface $kernel) { parent::__construct($kernel); $this->originalAutoExit = true; }
/** * Runs the current application. * * @param InputInterface $input An Input instance * @param OutputInterface $output An Output instance * * @return integer 0 if everything went fine, or an error code * * @throws \Exception When doRun returns Exception * * @api */ public function run(InputInterface $input = null, OutputInterface $output = null) { // make the parent method throw exceptions, so you can log it $this->setCatchExceptions(false);
if (null === $input) { $input = new ArgvInput(); } if (null === $output) { $output = new ConsoleOutput(); } try { $statusCode = parent::run($input, $output); } catch (\Exception $e) {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 }
$this->renderException($e, $output); } $statusCode = $e->getCode(); $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1; } if ($this->originalAutoExit) { if ($statusCode > 255) { $statusCode = 255; } // @codeCoverageIgnoreStart exit($statusCode); // @codeCoverageIgnoreEnd } return $statusCode; } public function setAutoExit($bool) { // parent property is private, so we need to intercept it in a setter $this->originalAutoExit = (Boolean) $bool; parent::setAutoExit($bool); }
In the code above, you disable exception catching so the parent run method will throw all exceptions. When an exception is caught, you simple log it by accessing the logger service from the service container and then handle the rest of the logic in the same way that the parent run method does (specifically, since the parent run6 method will not handle exceptions rendering and status code handling when catchExceptions is set to false, it has to be done in the overridden method). For the extended Application class to work properly with in console shell mode, you have to do a small trick to intercept the autoExit setter and store the setting in a different property, since the parent property is private. Now to be able to use your extended Application class you need to adjust the app/console script to use the new class instead of the default:
Listing 24-3
1 2 3 4 5 6 7 8
// app/console // ... // replace the following line: // use Symfony\Bundle\FrameworkBundle\Console\Application; use Acme\DemoBundle\Console\Application; // ...
That's it! Thanks to autoloader, your class will now be used instead of original one.
6. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Console/Application.html#run()
1 public function run(InputInterface $input = null, OutputInterface $output = null) 2 { 3 // make the parent method throw exceptions, so you can log it 4 $this->setCatchExceptions(false); 5 6 // store the autoExit value before resetting it - you'll need it later 7 $autoExit = $this->originalAutoExit; 8 $this->setAutoExit(false); 9 10 // ... 11 12 if ($autoExit) { 13 if ($statusCode > 255) { 14 $statusCode = 255; 15 } 16 17 // log non-0 exit codes along with command name 18 if ($statusCode !== 0) { 19 /** @var $logger LoggerInterface */ 20 $logger = $this->getKernel()->getContainer()->get('logger'); 21 $logger->warn(sprintf('Command `%s` exited with status code %d', 22 $this->getCommandName($input), $statusCode)); 23 } 24 25 // @codeCoverageIgnoreStart 26 exit($statusCode); 27 // @codeCoverageIgnoreEnd 28 } 29 30 return $statusCode; }
Chapter 25
All of the error templates live inside TwigBundle. To override the templates, simply rely on the standard method for overriding templates that live inside a bundle. For more information, see Overriding Bundle Templates. For example, to override the default error template that's shown to the end-user, create a new template located at app/Resources/TwigBundle/views/Exception/error.html.twig:
Listing 25-1
1 2 3 4 5 6 7 8 9 10 11
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>An Error Occurred: {{ status_text }}</title> </head> <body> <h1>Oops! An Error Occurred</h1> <h2>The server returned a "{{ status_code }} {{ status_text }}".</h2> </body> </html>
You must not use is_granted in your error pages (or layout used by your error pages), because the router runs before the firewall. If the router throws an exception (for instance, when the route does not match), then using is_granted will throw a further exception. You can use is_granted safely by saying {% if app.user and is_granted('...') %}.
If you're not familiar with Twig, don't worry. Twig is a simple, powerful and optional templating engine that integrates with Symfony2. For more information about Twig see Creating and using Templates.
In addition to the standard HTML error page, Symfony provides a default error page for many of the most common response formats, including JSON (error.json.twig), XML (error.xml.twig) and even JavaScript (error.js.twig), to name a few. To override any of these templates, just create a new file with the same name in the app/Resources/TwigBundle/views/Exception directory. This is the standard way of overriding any template that lives inside a bundle.
The debug-friendly exception pages shown to the developer can even be customized in the same way by creating templates such as exception.html.twig for the standard HTML exception page or exception.json.twig for the JSON exception page.
Chapter 26
1 2 3 4 5 6 7 8 9
1. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Controller/Controller.html
10 11 12 }
1 $this->forward('acme.hello.controller:indexAction');
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 26-4
You can also use annotations to configure routing using a controller defined as a service. See the FrameworkExtraBundle documentation for details.
2. https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
Listing 26-5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
If you look at the source code for the render function in Symfony's base Controller class3, you'll see that this method actually uses the templating service:
Listing 26-6
1 public function render($view, array $parameters = array(), Response $response = null) 2 { 3 return $this->container->get('templating')->renderResponse($view, $parameters, 4 $response); }
In a controller that's defined as a service, you can instead inject the templating service and use it directly:
Listing 26-7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
The service definition also needs modifying to specify the constructor argument:
Listing 26-8
1 # src/Acme/HelloBundle/Resources/config/services.yml 2 parameters:
3. https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
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.
Chapter 27
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 27-2
1 2 3 4 5 6 7 8 9 10 11
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 27-3
1 $kernel->loadClassCache('classes', '.php.cache');
Chapter 28
Deploying can be a complex and varied task depending on your setup and needs. This entry doesn't try to explain everything, but rather offers the most common requirements and ideas for deployment.
1. http://memcached.org/ 2. http://redis.io/
The --optimize-autoloader flag makes Composer's autoloader more performant by building a "class map". The --no-dev flag ensures that development packages are not installed in the production environment.
E) Other things!
There may be lots of other things that you need to do, depending on your setup: Running any database migrations Clearing your APC cache Running assets:install (taken care of already in composer.phar install) Add/edit CRON jobs Pushing assets to a CDN ...
The Tools
Capifony3: This tool provides a specialized set of tools on top of Capistrano, tailored specifically to symfony and Symfony2 projects. sf2debpkg4: This tool helps you build a native Debian package for your Symfony2 project. Magallanes5: This Capistrano-like deployment tool is built in PHP, and may be easier for PHP developers to extend for their needs. Bundles: There are many bundles that add deployment features6 directly into your Symfony2 console.
3. http://capifony.org/ 4. https://github.com/liip/sf2debpkg 5. https://github.com/andres-montanez/Magallanes
Basic scripting: You can of course use shell, Ant7, or any other build tool to script the deploying of your project. Platform as a Service Providers: PaaS is a relatively new way to deploy your application. Typically a PaaS will use a single configuration file in your project's root directory to determine how to build an environment on the fly that supports your software. One provider with confirmed Symfony2 support is PagodaBox8.
Looking for more? Talk to the community on the Symfony IRC channel9 #symfony (on freenode) for more information.
Chapter 29
Basic Setup
First, create a simple Doctrine Entity class to work with:
Listing 29-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/** * @ORM\Entity */ class Document { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ public $id; /** * @ORM\Column(type="string", length=255)
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 }
The Document entity has a name and it is associated with a file. The path property stores the relative path to the file and is persisted to the database. The getAbsolutePath() is a convenience method that returns the absolute path to the file while the getWebPath() is a convenience method that returns the web path, which can be used in a template to link to the uploaded file.
If you have not done so already, you should probably read the file type documentation first to understand how the basic upload process works.
If you're using annotations to specify your validation rules (as shown in this example), be sure that you've enabled validation by annotation (see validation configuration).
To handle the actual file upload in the form, use a "virtual" file field. For example, if you're building your form directly in a controller, it might look like this:
Listing 29-2
1 public function uploadAction() 2 { 3 // ... 4 5 $form = $this->createFormBuilder($document) 6 ->add('name') 7 ->add('file') 8 ->getForm(); 9 10 // ... 11 }
Next, create this property on your Document class and add some validation rules:
Listing 29-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
use Symfony\Component\HttpFoundation\File\UploadedFile;
// ... class Document { /** * @Assert\File(maxSize="6000000") */ private $file; /** * Sets file. * * @param UploadedFile $file */ public function setFile(UploadedFile $file = null) { $this->file = $file; } /** * Get file. * * @return UploadedFile */ public function getFile() { return $this->file; }
}
Listing 29-4
As you are using the File constraint, Symfony2 will automatically guess that the form field is a file upload input. That's why you did not have to set it explicitly when creating the form above (->add('file')).
The following controller shows you how to handle the entire process:
Listing 29-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
// ... use Acme\DemoBundle\Entity\Document; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; // ... /** * @Template() */ public function uploadAction(Request $request) { $document = new Document(); $form = $this->createFormBuilder($document) ->add('name') ->add('file') ->getForm();
$form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($document); $em->flush(); return $this->redirect($this->generateUrl(...)); } return array('form' => $form->createView()); }
The previous controller will automatically persist the Document entity with the submitted name, but it will do nothing about the file and the path property will be blank. An easy way to handle the file upload is to move it just before the entity is persisted and then set the path property accordingly. Start by calling a new upload() method on the Document class, which you'll create in a moment to handle the file upload:
Listing 29-6
The upload() method will take advantage of the UploadedFile1 object, which is what's returned after a file field is submitted:
Listing 29-7
1. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/File/UploadedFile.html
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 }
// the file property can be empty if the field is not required if (null === $this->getFile()) { return; } // use the original file name here but you should // sanitize it at least to avoid any security issues // move takes the target directory and then the // target filename to move to $this->getFile()->move( $this->getUploadRootDir(), $this->getFile()->getClientOriginalName() ); // set the path property to the filename where you've saved the file $this->path = $this->getFile()->getClientOriginalName(); // clean up the file property as you won't need it anymore $this->file = null;
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9 10
use Symfony\Component\HttpFoundation\File\UploadedFile;
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
/** * Sets file. * * @param UploadedFile $file */ public function setFile(UploadedFile $file = null) { $this->file = $file; // check if we have an old image path if (isset($this->path)) { // store the old name to delete after the update $this->temp = $this->path; $this->path = null; } else { $this->path = 'initial'; } } /** * @ORM\PrePersist() * @ORM\PreUpdate() */ public function preUpload() { if (null !== $this->getFile()) { // do whatever you want to generate a unique name $filename = sha1(uniqid(mt_rand(), true)); $this->path = $filename.'.'.$this->getFile()->guessExtension(); } } /** * @ORM\PostPersist() * @ORM\PostUpdate() */ public function upload() { if (null === $this->getFile()) { return; } // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error $this->getFile()->move($this->getUploadRootDir(), $this->path); // check if we have an old image if (isset($this->temp)) { // delete the old image unlink($this->getUploadRootDir().'/'.$this->temp); // clear the temp image path $this->temp = null; } $this->file = null;
}
/** * @ORM\PostRemove() */
70 71 72 73 74 75 76 }
The class now does everything you need: it generates a unique filename before persisting, moves the file after persisting, and removes the file if the entity is ever deleted. Now that the moving of the file is handled atomically by the entity, the call to $document->upload() should be removed from the controller:
Listing 29-10
The @ORM\PrePersist() and @ORM\PostPersist() event callbacks are triggered before and after the entity is persisted to the database. On the other hand, the @ORM\PreUpdate() and @ORM\PostUpdate() event callbacks are called when the entity is updated.
The PreUpdate and PostUpdate callbacks are only triggered if there is a change in one of the entity's field that are persisted. This means that, by default, if you modify only the $file property, these events will not be triggered, as the property itself is not directly persisted via Doctrine. One solution would be to use an updated field that's persisted to Doctrine, and to modify it manually when changing the file.
1 2 3 4 5 6 7 8 9 10 11 12 13
use Symfony\Component\HttpFoundation\File\UploadedFile;
/** * @ORM\Entity * @ORM\HasLifecycleCallbacks */ class Document { private $temp; /** * Sets file. *
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
* @param UploadedFile $file */ public function setFile(UploadedFile $file = null) { $this->file = $file; // check if we have an old image path if (is_file($this->getAbsolutePath())) { // store the old name to delete after the update $this->temp = $this->getAbsolutePath(); } else { $this->path = 'initial'; } } /** * @ORM\PrePersist() * @ORM\PreUpdate() */ public function preUpload() { if (null !== $this->getFile()) { $this->path = $this->getFile()->guessExtension(); } } /** * @ORM\PostPersist() * @ORM\PostUpdate() */ public function upload() { if (null === $this->getFile()) { return; } // check if we have an old image if (isset($this->temp)) { // delete the old image unlink($this->temp); // clear the temp image path $this->temp = null; } // you must throw an exception here if the file cannot be moved // so that the entity is not persisted to the database // which the UploadedFile move() method does $this->getFile()->move( $this->getUploadRootDir(), $this->id.'.'.$this->getFile()->guessExtension() );
$this->setFile(null); }
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 }
$this->temp = $this->getAbsolutePath(); }
You'll notice in this case that you need to do a little bit more work in order to remove the file. Before it's removed, you must store the file path (since it depends on the id). Then, once the object has been fully removed from the database, you can safely delete the file (in PostRemove).
Chapter 30
Chapter 30: How to use Doctrine Extensions: Timestampable, Sluggable, Translatable, etc. | 111
Chapter 31
1 doctrine: 2 dbal: 3 default_connection: default 4 connections: 5 default: 6 driver: pdo_sqlite 7 memory: true 8 9 services: 10 my.listener: 11 class: Acme\SearchBundle\EventListener\SearchIndexer 12 tags:
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html
13 14 15 16 17 18 19 20 21
- { name: doctrine.event_listener, event: postPersist } my.listener2: class: Acme\SearchBundle\EventListener\SearchIndexer2 tags: - { name: doctrine.event_listener, event: postPersist, connection: default } my.subscriber: class: Acme\SearchBundle\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
// perhaps you only want to act on some "Product" entity if ($entity instanceof Product) { // ... do something with the Product }
} }
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).
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
// perhaps you only want to act on some "Product" entity if ($entity instanceof Product) { // ... do something with the Product }
} }
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 System2 in the Doctrine documentation.
2. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html
Chapter 32
This article is about Doctrine DBAL's layer. 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.
1 # app/config/config.yml 2 doctrine: 3 dbal: 4 driver: pdo_mysql 5 dbname: Symfony2 6 user: root 7 password: null 8 charset: UTF8
For full DBAL configuration options, see Doctrine DBAL Configuration. You can then access the Doctrine DBAL connection by accessing the database_connection service:
Listing 32-2
1 class UserController extends Controller 2 { 3 public function indexAction() 4 { 5 $conn = $this->get('database_connection'); 6 $users = $conn->fetchAll('SELECT * FROM users'); 7 8 // ... 9 } 10 }
1 # app/config/config.yml 2 doctrine: 3 dbal: 4 connections: 5 default: 6 // Other connections parameters 7 mapping_types: 8 enum: string
4. http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#custom-mapping-types
Chapter 33
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 33-1
1 CREATE TABLE `blog_post` ( 2 `id` bigint(20) NOT NULL AUTO_INCREMENT, 3 `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, 4 `content` longtext COLLATE utf8_unicode_ci NOT NULL, 5 `created_at` datetime NOT NULL, 6 PRIMARY KEY (`id`) 7 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 8 9 CREATE TABLE `blog_comment` ( 10 `id` bigint(20) NOT NULL AUTO_INCREMENT, 11 `post_id` bigint(20) NOT NULL, 12 `author` varchar(20) COLLATE utf8_unicode_ci NOT NULL, 13 `content` longtext COLLATE utf8_unicode_ci NOT NULL, 14 `created_at` datetime NOT NULL,
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/tools.html#reverse-engineering
15 PRIMARY KEY (`id`), 16 KEY `blog_comment_post_id_idx` (`post_id`), 17 CONSTRAINT `blog_post_id` FOREIGN KEY (`post_id`) REFERENCES `blog_post` (`id`) ON 18 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 33-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
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="Acme\BlogBundle\Entity\BlogPost" table="blog_post"> <id name="id" type="bigint" column="id"> <generator strategy="IDENTITY"/> </id> <field name="title" type="string" column="title" length="100" nullable="false"/> <field name="content" type="text" column="content" nullable="false"/> <field name="createdAt" type="datetime" column="created_at" nullable="false"/> </entity> </doctrine-mapping>
Once the metadata files are generated, you can ask Doctrine to build related entity classes by executing the following two commands.
Listing 33-4
The first command generates entity classes with annotation mappings. But if you want to use yml or xml mapping instead of annotations, you should execute the second command only.
If you want to use annotations, you can safely delete the XML (or YAML) files after running these two commands.
For example, the newly created BlogComment entity class looks as follow:
Listing 33-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 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 oneToMany relationship, you will need to add it manually into the entity or to the generated xml or yml files. Add a section on the specific entities for oneToMany defining the inversedBy and the mappedBy pieces.
Chapter 34
The following configuration code shows how you can configure two entity managers:
Listing 34-1
1 doctrine: 2 dbal: 3 default_connection: default 4 connections: 5 default: 6 driver: "%database_driver%" 7 host: "%database_host%" 8 port: "%database_port%" 9 dbname: "%database_name%" 10 user: "%database_user%" 11 password: "%database_password%" 12 charset: UTF8 13 customer: 14 driver: "%database_driver2%" 15 host: "%database_host2%" 16 port: "%database_port2%" 17 dbname: "%database_name2%" 18 user: "%database_user2%" 19 password: "%database_password2%" 20 charset: UTF8
Chapter 34: How to work with Multiple Entity Managers and Connections | 121
21 22 23 24 25 26 27 28 29 30 31 32 33
orm: default_entity_manager: default entity_managers: default: connection: default mappings: AcmeDemoBundle: ~ 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 AcmeDemoBundle 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
# Play only with "default" connection $ php app/console doctrine:database:create # Play only with "customer" connection $ php app/console doctrine:database:create --connection=customer
1 2 3 4 5
# Play only with "default" mappings $ php app/console doctrine:schema:update --force # Play only with "customer" mappings $ php app/console doctrine:schema:update --force --em=customer
If you do omit the entity manager's name when asking for it, the default entity manager (i.e. default) is returned:
Listing 34-4
1 class UserController extends Controller 2 { 3 public function indexAction() 4 { 5 // both return the "default" em 6 $em = $this->get('doctrine')->getManager(); 7 $em = $this->get('doctrine')->getManager('default'); 8 9 $customerEm = $this->get('doctrine')->getManager('customer'); 10 } 11 }
Chapter 34: How to work with Multiple Entity Managers and Connections | 122
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 call:
Listing 34-5
1 class UserController extends Controller 2 { 3 public function indexAction() 4 { 5 // Retrieves a repository managed by the "default" em 6 $products = $this->get('doctrine') 7 ->getRepository('AcmeStoreBundle:Product') 8 ->findAll() 9 ; 10 11 // Explicit way to deal with the "default" em 12 $products = $this->get('doctrine') 13 ->getRepository('AcmeStoreBundle:Product', 'default') 14 ->findAll() 15 ; 16 17 // Retrieves a repository managed by the "customer" em 18 $customers = $this->get('doctrine') 19 ->getRepository('AcmeCustomerBundle:Customer', 'customer') 20 ->findAll() 21 ; 22 } 23 }
Chapter 34: How to work with Multiple Entity Managers and Connections | 123
Chapter 35
1 # app/config/config.yml 2 doctrine: 3 orm: 4 # ... 5 entity_managers: 6 default: 7 # ... 8 dql: 9 string_functions: 10 test_string: Acme\HelloBundle\DQL\StringFunction 11 second_string: Acme\HelloBundle\DQL\SecondStringFunction 12 numeric_functions: 13 test_numeric: Acme\HelloBundle\DQL\NumericFunction 14 datetime_functions: 15 test_datetime: Acme\HelloBundle\DQL\DatetimeFunction
1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html
Chapter 36
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
Let's use the following basic entities (which are incomplete for brevity) to explain how to set up and use the RTEL. A Customer entity:
Listing 36-1
Chapter 36: How to Define Relationships with Abstract Classes and Interfaces | 125
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 our example, any methods defined in the InvoiceSubjectInterface // are already implemented in the BaseCustomer }
An Invoice entity:
Listing 36-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 36-3
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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
Chapter 36: How to Define Relationships with Abstract Classes and Interfaces | 126
14 15 16 17 18 19 20 21 }
// 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 36-4
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 36: How to Define Relationships with Abstract Classes and Interfaces | 127
Chapter 37
New in version 2.3: The base mapping compiler pass was added in Symfony 2.3. The Doctrine bundles support it from DoctrineBundle >= 1.2.1, MongoDBBundle >= 3.0.0, PHPCRBundle >= 1.0.0-alpha2 and the (unversioned) CouchDBBundle supports the compiler pass since the CouchDB Mapping Compiler Pass pull request1 was merged.
If you want your bundle to support older versions of Symfony and Doctrine, you can provide a copy of the compiler pass in your bundle. See for example the FOSUserBundle mapping configuration2 addRegisterMappingsPass. In your bundle class, write the following code to register the compiler pass. This one is written for the FOSUserBundle, so parts of it will need to be adapted for your case:
Listing 37-1
1 2 3 4 5 6 7
1. https://github.com/doctrine/DoctrineCouchDBBundle/pull/27 2. https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/FOSUserBundle.php
Chapter 37: How to provide model classes for several Doctrine implementations | 128
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
public function build(ContainerBuilder $container) { parent::build($container); // ... $modelDir = realpath(__DIR__.'/Resources/config/doctrine/model'); $mappings = array( $modelDir => 'FOS\UserBundle\Model', ); $ormCompilerClass = 'Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass'; if (class_exists($ormCompilerClass)) { $container->addCompilerPass( DoctrineOrmMappingsPass::createXmlMappingDriver( $mappings, array('fos_user.model_manager_name'), 'fos_user.backend_type_orm' )); } $mongoCompilerClass = 'Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass'; if (class_exists($mongoCompilerClass)) { $container->addCompilerPass( DoctrineMongoDBMappingsPass::createXmlMappingDriver( $mappings, array('fos_user.model_manager_name'), 'fos_user.backend_type_mongodb' )); } $couchCompilerClass = 'Doctrine\Bundle\CouchDBBundle\DependencyInjection\Compiler\DoctrineCouchDBMappingsPass'; if (class_exists($couchCompilerClass)) { $container->addCompilerPass( DoctrineCouchDBMappingsPass::createXmlMappingDriver( $mappings, array('fos_user.model_manager_name'), 'fos_user.backend_type_couchdb' )); } $phpcrCompilerClass = 'Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass'; if (class_exists($phpcrCompilerClass)) { $container->addCompilerPass( DoctrinePhpcrMappingsPass::createXmlMappingDriver( $mappings, array('fos_user.model_manager_name'), 'fos_user.backend_type_phpcr' )); } } }
Chapter 37: How to provide model classes for several Doctrine implementations | 129
Note the class_exists3 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 above example, the FOSUserBundle stores the manager name that's being used under the fos_user.model_manager_name parameter. The compiler pass will append the parameter 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.
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 simply taken from the DoctrineOrmMappingsPass and adapted to use the DefaultFileLocator instead of the SymfonyFileLocator:
Listing 37-2
1 2 3 4 5 6 7 8 9 10 11 12 13
private function buildMappingCompilerPass() { $arguments = array(array(realpath(__DIR__ . '/Resources/config/doctrine-base')), '.orm.xml'); $locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator', $arguments); $driver = new Definition('Doctrine\ORM\Mapping\Driver\XmlDriver', array($locator)); return new DoctrineOrmMappingsPass( $driver, array('Full\Namespace'), array('your_bundle.manager_name'), 'your_bundle.orm_enabled' ); }
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.
3. http://php.net/manual/en/function.class-exists.php
Chapter 37: How to provide model classes for several Doctrine implementations | 130
Chapter 38
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
/** * @ORM\Entity * @UniqueEntity(fields="email", message="Email already taken") */ class User { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank() * @Assert\Email() */ protected $email;
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 }
This User entity contains three fields and two of them (email and plainPassword) should display on the form. The email property must be unique in the database, this is enforced by adding this validation at the top of the class.
If you want to integrate this User within the security system, you need to implement the UserInterface of the security component.
1. http://symfony.com/blog/cve-2013-5750-security-issue-in-fosuserbundle-login-form
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
There are just two fields: email and plainPassword (repeated to confirm the entered password). The data_class option tells the form the name of data class (i.e. your User entity).
To explore more things about the form component, read Forms.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 }
You don't need to use special method for embedding the UserType form. A form is a field, too - so you can add this like any other field, with the expectation that the Registration.user property will hold an instance of the User class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
1 {# src/Acme/AccountBundle/Resources/views/Account/register.html.twig #} 2 {{ form(form) }}
Next, create the controller which handles the form submission. This performs the validation and saves the data into the database:
Listing 38-7
1 public function createAction(Request $request) 2 { 3 $em = $this->getDoctrine()->getEntityManager(); 4 5 $form = $this->createForm(new RegistrationType(), new Registration()); 6
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 }
$form->handleRequest($request); if ($form->isValid()) { $registration = $form->getData(); $em->persist($registration->getUser()); $em->flush(); return $this->redirect(...); } return $this->render( 'AcmeAccountBundle:Account:register.html.twig', array('form' => $form->createView()) );
1 # src/Acme/AccountBundle/Resources/config/routing.yml 2 account_register: 3 pattern: /register 4 defaults: { _controller: AcmeAccountBundle:Account:register } 5 6 account_create: 7 pattern: /register/create 8 defaults: { _controller: AcmeAccountBundle:Account:create }
Chapter 39
Configuration
Before using Swiftmailer, be sure to include its configuration. The only mandatory configuration parameter is transport:
Listing 39-2
1 # app/config/config.yml 2 swiftmailer: 3 transport: smtp 4 encryption: ssl 5 auth_mode: login 6 host: smtp.gmail.com
1. http://swiftmailer.org/
7 8
username: password:
your_username your_password
The majority of the Swiftmailer configuration deals with how the messages themselves should be delivered. The following configuration attributes are available: transport (smtp, mail, sendmail, or gmail) username password host port encryption (tls, or ssl) auth_mode (plain, login, or cram-md5) spool type (how to queue the messages, file or memory is supported, see How to Spool Emails) path (where to store the messages) delivery_address (an email address where to send ALL emails) disable_delivery (set to true to disable delivery completely)
Sending Emails
The Swiftmailer 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 39-3
1 public function indexAction($name) 2 { 3 $message = \Swift_Message::newInstance() 4 ->setSubject('Hello Email') 5 ->setFrom('[email protected]') 6 ->setTo('[email protected]') 7 ->setBody( 8 $this->renderView( 9 'HelloBundle:Hello:email.txt.twig', 10 array('name' => $name) 11 ) 12 ) 13 ; 14 $this->get('mailer')->send($message); 15 16 return $this->render(...); 17 }
To keep things decoupled, the email body has been stored in a template and rendered with the renderView() method. The $message object supports many more options, such as including attachments, adding HTML content, and much more. Fortunately, Swiftmailer covers the topic of Creating Messages2 in great detail in its documentation.
2. http://swiftmailer.org/docs/messages.html
Several other cookbook articles are available related to sending emails in Symfony2: How to use Gmail to send Emails How to Work with Emails During Development How to Spool Emails
Chapter 40
In the development configuration file, change the transport setting to gmail and set the username and password to the Google credentials:
Listing 40-1
You're done!
If you are using the Symfony Standard Edition, configure the parameters at parameters.yml:
Listing 40-2
1 # app/config/parameters.yml 2 parameters: 3 ... 4 mailer_transport: gmail 5 mailer_host: ~ 6 mailer_user: your_gmail_username 7 mailer_password: your_gmail_password
The gmail transport is simply a shortcut that uses the smtp transport and sets encryption, auth_mode and host to work with Gmail.
Chapter 41
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 41-1
If you'd also like to disable deliver in the dev environment, simply add this same configuration to the config_dev.yml file.
1 public function indexAction($name) 2 { 3 $message = \Swift_Message::newInstance() 4 ->setSubject('Hello Email') 5 ->setFrom('[email protected]') 6 ->setTo('[email protected]') 7 ->setBody( 8 $this->renderView( 9 'HelloBundle:Hello:email.txt.twig', 10 array('name' => $name) 11 ) 12 ) 13 ; 14 $this->get('mailer')->send($message); 15 16 return $this->render(...); 17 }
In the dev environment, the email will instead be sent to [email protected]. Swiftmailer 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. Swiftmailer 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.
Listing 41-4
Chapter 42
5 6
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 42-3
1 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 42-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 43
1 public function sendEmailAction($name) 2 { 3 $message = \Swift_Message::newInstance() 4 ->setSubject('Hello Email') 5 ->setFrom('[email protected]') 6 ->setTo('[email protected]') 7 ->setBody('You should see me from the profiler!') 8 ; 9 10 $this->get('mailer')->send($message); 11 12 return $this->render(...); 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 send on the previous request:
Listing 43-2
1. http://swiftmailer.org/
Chapter 43: How to test that an Email is sent in a functional Test | 145
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
// 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');
// Asserting e-mail data $this->assertInstanceOf('Swift_Message', $message); $this->assertEquals('Hello Email', $message->getSubject()); $this->assertEquals('[email protected]', key($message->getFrom())); $this->assertEquals('[email protected]', key($message->getTo())); $this->assertEquals( 'You should see me from the profiler!', $message->getBody() );
} }
Chapter 43: How to test that an Email is sent in a functional Test | 146
Chapter 44
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 12 13
namespace Acme\DemoBundle\Controller; use Acme\DemoBundle\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 * $controller passed can be either a class or a Closure. This is not usual in 23 Symfony2 but it may happen. 24 * If it is a class, it comes in array format 25 */ 26 if (!is_array($controller)) { 27 return; 28 } 29 30 if ($controller[0] instanceof TokenAuthenticatedController) { 31 $token = $event->getRequest()->query->get('token'); 32 if (!in_array($token, $this->tokens)) { 33 throw new AccessDeniedHttpException('This action needs a valid token!'); 34 } 35 } 36 } }
1 # app/config/config.yml (or inside your services.yml) 2 services: 3 demo.tokens.action_listener: 4 class: Acme\DemoBundle\EventListener\TokenListener 5 arguments: ["%tokens%"] 6 tags: 7 - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
With this configuration, your TokenListener onKernelController method will be executed on each request. If the controller that is about to be executed implements TokenAuthenticatedController, token authentication is applied. This lets you have a "before" filter on any controller that you want.
5 6 7 8 9 10 11 12 13 14 }
if ($controller[0] instanceof TokenAuthenticatedController) { $token = $event->getRequest()->query->get('token'); if (!in_array($token, $this->tokens)) { throw new AccessDeniedHttpException('This action needs a valid token!'); }
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 44-7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// add the new use statement at the top of your file use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
public function onKernelResponse(FilterResponseEvent $event) { // check to see if onKernelController marked this as a token "auth'ed" request if (!$token = $event->getRequest()->attributes->get('auth_token')) { return; } $response = $event->getResponse();
// create a hash and set it as a response header $hash = sha1($response->getContent().$token); $response->headers->set('X-CONTENT-HASH', $hash);
}
Finally, a second "tag" is needed on the service definition to notify Symfony that the onKernelResponse event should be notified for the kernel.response event:
Listing 44-8
1 # app/config/config.yml (or inside your services.yml) 2 services: 3 demo.tokens.action_listener: 4 class: Acme\DemoBundle\EventListener\TokenListener 5 arguments: ["%tokens%"] 6 tags: 7 - { name: kernel.event_listener, event: kernel.controller, method: 8 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 45
1 class Foo 2 { 3 // ... 4 5 public function __call($method, $arguments) 6 { 7 // create an event named 'foo.method_is_not_found' 8 $event = new HandleUndefinedMethodEvent($this, $method, $arguments); 9 $this->dispatcher->dispatch('foo.method_is_not_found', $event); 10 11 // no listener was able to process the event? The method does not exist 12 if (!$event->isProcessed()) { 13 throw new \Exception(sprintf('Call to undefined method %s::%s.', 14 get_class($this), $method)); 15 } 16 17 // return the listener returned value 18 return $event->getReturnValue(); 19 } }
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 45-2
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 }
public function __construct($subject, $method, $arguments) { $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 45-3
1 class Bar 2 { 3 public function onFooMethodIsNotFound(HandleUndefinedMethodEvent $event) 4 { 5 // only respond to the calls to the 'bar' method 6 if ('bar' != $event->getMethod()) { 7 // allow another listener to take care of this unknown method 8 return;
9 10 11 12 13 14 15 16 17 18 19 20 21 22 }
// the subject object (the foo instance) $foo = $event->getSubject(); // the bar method arguments $arguments = $event->getArguments(); // ... do something // set the return value $event->setReturnValue($someValue);
}
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 45-4
Chapter 46
1 class Foo 2 { 3 // ... 4 5 public function send($foo, $bar) 6 { 7 // do something before the method 8 $event = new FilterBeforeSendEvent($foo, $bar); 9 $this->dispatcher->dispatch('foo.pre_send', $event); 10 11 // get $foo and $bar from the event, they may have been modified 12 $foo = $event->getFoo(); 13 $bar = $event->getBar(); 14 15 // the real method implementation is here 16 $ret = ...; 17 18 // do something after the method 19 $event = new FilterSendReturnValue($ret); 20 $this->dispatcher->dispatch('foo.post_send', $event); 21 22 return $event->getReturnValue(); 23 } 24 }
Chapter 46: How to customize a Method Behavior without using Inheritance | 154
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. For example, assuming the FilterSendReturnValue has a setReturnValue method, one listener might look like this:
Listing 46-2
1 public function onFooPostSend(FilterSendReturnValue $event) 2 { 3 $ret = $event->getReturnValue(); 4 // modify the original ``$ret`` value 5 6 $event->setReturnValue($ret); 7 }
Chapter 46: How to customize a Method Behavior without using Inheritance | 155
Chapter 47
1 {{ form_row(form.age) }}
You can also render each of the three parts of the field individually:
Listing 47-2
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 47-3
1 <div> 2 <label for="form_age">Age</label> 3 <ul> 4 <li>This field is required</li> 5 </ul> 6 <input type="number" id="form_age" name="form[age]" /> 7 </div>
To quickly prototype and test a form, you can render the entire form with just one line:
Listing 47-4
1 {{ form_widget(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.
1 {{ form_widget(form.age) }}
renders:
Listing 47-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.twig2 template. In PHP it would rather be the integer_widget.html.php file located in the FrameworkBundle/ Resources/views/Form folder. The default implementation of the integer_widget fragment looks like this:
Listing 47-7
As you can see, this fragment itself renders another fragment - form_widget_simple:
Listing 47-8
1 {# form_div_layout.html.twig #} 2 {% block form_widget_simple %} 3 {% set type = type|default('text') %} 4 <input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty 5 %}value="{{ value }}" {% endif %}/> {% endblock form_widget_simple %}
1. https://github.com/symfony/symfony/blob/2.3/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig 2. https://github.com/symfony/symfony/blob/2.3/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
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.
Both methods have the same effect but are better in different situations.
1 {% extends '::base.html.twig' %} 2
3 4 5 6 7 8 9 10 11 12 13 14 15 16
{% 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 {# src/Acme/DemoBundle/Resources/views/Form/fields.html.twig #} 2 {% block integer_widget %} 3 <div class="integer_widget"> 4 {% set type = type|default('number') %} 5 {{ block('form_widget_simple') }} 6 </div> 7 {% 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 47-11
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.
Child Forms
You can also apply a form theme to a specific child of your form:
Listing 47-12
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 47-13
1 <!-- src/Acme/DemoBundle/Resources/views/Form/integer_widget.html.php --> 2 <div class="integer_widget"> 3 <?php echo $view['form']->block($form, 'form_widget_simple', array('type' => 4 isset($type) ? $type : "number")) ?> </div>
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 47-15
When the form.age widget is rendered, Symfony will use the customized integer_widget.html.php template and the input tag will be wrapped in the div element. If you want to apply a theme to a specific child form, pass it to the setTheme method:
Listing 47-16
3. https://github.com/symfony/symfony/blob/2.3/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig
Now, when the blocks from form_div_layout.html.twig4 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 47-18
1 2 3 4 5 6 7 8
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 using the following configuration, any customized form blocks inside the AcmeDemoBundle:Form:fields.html.twig template will be used globally when a form is rendered.
Listing 47-20
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 47-21
4. https://github.com/symfony/symfony/blob/2.3/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_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 47-22
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 src/Acme/DemoBundle/ Resources/views/Form folder will be used globally when a form is rendered.
Listing 47-23
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 47-24
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 47-25
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
{% form_theme form _self %} {% block _product_name_widget %} <div class="text_widget"> {{ block('form_widget_simple') }} </div> {% endblock %} {{ form_widget(form.name) }}
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.
You can also override the markup for an entire field row using the same method:
Listing 47-27
1 2 3 4 5 6 7 8 9 10
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 47-28
1 {{ form_errors(form.age) }}
Listing 47-29
To override how errors are rendered for all fields, simply copy, paste and customize the form_errors fragment.
Listing 47-30
1 {# form_errors.html.twig #} 2 {% block form_errors %} 3 {% spaceless %} 4 {% if errors|length > 0 %} 5 <ul> 6 {% for error in errors %} 7 <li>{{ error.message }}</li> 8 {% endfor %} 9 </ul> 10 {% endif %} 11 {% endspaceless %} 12 {% endblock form_errors %}
You can also customize the error output for just one specific field type. For example, 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 47-31
1 {{ form_errors(form) }}
To customize only the markup used for these errors, follow the same directions as above, but now call the block form_errors (Twig) / the file form_errors.html.php (PHP). Now, when errors for the form type are rendered, your customized fragment will be used instead of the default form_errors.
1 {# form_row.html.twig #} 2 {% block form_row %} 3 <div class="form_row"> 4 {{ form_label(form) }} 5 {{ form_errors(form) }} 6 {{ form_widget(form) }} 7 </div> 8 {% endblock form_row %}
1 {% use 'form_div_layout.html.twig' with form_label as base_form_label %} 2 3 {% block form_label %} 4 {{ block('base_form_label') }} 5 6 {% if required %} 7 <span class="required" title="This field is required">*</span> 8 {% endif %} 9 {% endblock %}
In Twig, if you're making the form customization inside a separate template, use the following:
Listing 47-34
1 {% extends 'form_div_layout.html.twig' %} 2 3 {% block form_label %} 4 {{ parent() }} 5 6 {% if required %} 7 <span class="required" title="This field is required">*</span> 8 {% endif %} 9 {% endblock %}
When using PHP as a templating engine you have to copy the content from the original template:
Listing 47-35
1 2 3 4 5 6 7 8 9 10 11 12
<!-- form_label.html.php --> <!-- original content --> <?php if ($required) { $label_attr['class'] = trim((isset($label_attr['class']) ? $label_attr['class'] : '').' required'); } ?> <?php if (!$compound) { $label_attr['for'] = $id; } ?> <?php if (!$label) { $label = $view['form']->humanize($name); } ?> <label <?php foreach ($label_attr as $k => $v) { printf('%s="%s" ', $view->escape($k), $view->escape($v)); } ?>><?php echo $view->escape($view['translator']->trans($label, array(), $translation_domain)) ?></label> <!-- customization --> <?php if ($required) : ?> <span class="required" title="This field is required">*</span> <?php endif ?>
1 {% use 'form_div_layout.html.twig' with form_widget_simple as base_form_widget_simple %} 2 3 {% block form_widget_simple %} 4 {{ block('base_form_widget_simple') }} 5 6 {% if help is defined %} 7 <span class="help">{{ help }}</span> 8 {% endif %} 9 {% endblock %}
In twig, If you're making the form customization inside a separate template, use the following:
Listing 47-37
1 {% extends 'form_div_layout.html.twig' %} 2 3 {% block form_widget_simple %} 4 {{ parent() }} 5 6 {% if help is defined %} 7 <span class="help">{{ help }}</span> 8 {% endif %} 9 {% endblock %}
When using PHP as a templating engine you have to copy the content from the original template:
Listing 47-38
1 2 3 4 5 6 7 8 9 10 11 12 13
<!-- form_widget_simple.html.php --> <!-- Original content --> <input type="<?php echo isset($type) ? $view->escape($type) : 'text' ?>" <?php if (!empty($value)): ?>value="<?php echo $view->escape($value) ?>"<?php endif ?> <?php echo $view['form']->block($form, 'widget_attributes') ?> /> <!-- Customization --> <?php if (isset($help)) : ?> <span class="help"><?php echo $view->escape($help) ?></span> <?php endif ?>
1 {# render a widget, but add a "foo" class to it #} 2 {{ form_widget(form.name, { 'attr': {'class': 'foo'} }) }}
The array passed as the second argument contains form "variables". For more details about this concept in Twig, see More about Form Variables.
Chapter 48
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 62 63 64 65 66 67 68 }
{ $this->om = $om; }
/** * Transforms an object (issue) to a string (number). * * @param Issue|null $issue * @return string */ public function transform($issue) { if (null === $issue) { return ""; }
return $issue->getNumber(); }
/** * Transforms a string (number) to an object (issue). * * @param string $number * * @return Issue|null * * @throws TransformationFailedException if object (issue) is not found. */ public function reverseTransform($number) { if (!$number) { return null; }
$issue = $this->om ->getRepository('AcmeTaskBundle:Issue') ->findOneBy(array('number' => $number)) ; if (null === $issue) { throw new TransformationFailedException(sprintf( 'An issue with number "%s" does not exist!', $number )); } return $issue; }
If you want a new issue to be created when an unknown number is entered, you can instantiate it rather than throwing the TransformationFailedException.
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
use Symfony\Component\Form\FormBuilderInterface; use Acme\TaskBundle\Form\DataTransformer\IssueToNumberTransformer; class TaskType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // ...
// this assumes that the entity manager was passed in as an option $entityManager = $options['em']; $transformer = new IssueToNumberTransformer($entityManager); // add a normal text field, but add your transformer to it $builder->add( $builder->create('issue', 'text') ->addModelTransformer($transformer) );
} public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Acme\TaskBundle\Entity\Task', )); $resolver->setRequired(array( 'em', )); $resolver->setAllowedTypes(array( 'em' => 'Doctrine\Common\Persistence\ObjectManager', ));
// ...
}
// ...
}
This example requires that you pass in the entity manager as an option when creating your form. Later, you'll learn how you could create a custom issue field type to avoid needing to do this in your controller:
Listing 48-3
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 framework 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.
Notice that adding a transformer requires using a slightly more complicated syntax when adding the field. The following is wrong, as the transformer would be applied to the entire form, instead of just this field:
Listing 48-4
1 // THIS IS WRONG - TRANSFORMER WILL BE APPLIED TO THE ENTIRE FORM 2 // see above example for correct code 3 $builder->add('issue', 'text') 4 ->addModelTransformer($transformer);
The difference between the transformers is subtle and you should always think about what the "norm" data for a field should really be. For example, the "norm" data for a text field is a string, but is a DateTime object for a date field.
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
/** * @param ObjectManager $om */ public function __construct(ObjectManager $om) { $this->om = $om; }
public function buildForm(FormBuilderInterface $builder, array $options) { $transformer = new IssueToNumberTransformer($this->om); $builder->addModelTransformer($transformer); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'invalid_message' => 'The selected issue does not exist', )); } public function getParent() { return 'text'; }
43 44 45 46 47 }
Next, register your type as a service and tag it with form.type so that it's recognized as a custom field type:
Listing 48-6
1 services: 2 acme_demo.type.issue_selector: 3 class: Acme\TaskBundle\Form\Type\IssueSelectorType 4 arguments: ["@doctrine.orm.entity_manager"] 5 tags: 6 - { name: form.type, alias: issue_selector }
Now, whenever you need to use your special issue_selector field type, it's quite easy:
Listing 48-7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Chapter 49
1 2 3 4 5 6 7 8 9 10 11 12
Chapter 49: How to Dynamically Modify Forms Using Form Events | 174
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 }
$builder->add('price'); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Acme\DemoBundle\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 Event Dispatcher 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
// ...
}
Chapter 49: How to Dynamically Modify Forms Using Form Events | 175
Listing 49-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
// // // if
} } }
check if the product object is "new" If you didn't pass any data to the form, the data is "null". This should be considered a new "Product" (!$data || !$data->getId()) { $form->add('name', 'text');
The FormEvents::PRE_SET_DATA line actually resolves to the string form.pre_set_data. FormEvents2 serves an organizational purpose. It is a centralized location in which you can find all of the various form events available.
You can view the full list of form events via the FormEvents3 class.
Chapter 49: How to Dynamically Modify Forms Using Form Events | 176
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
class FriendMessageFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('subject', 'text') ->add('body', 'textarea') ; $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){ // ... add a choice list of friends of the current application user }); } public function getName() { return 'acme_friend_message'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { } }
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 49-5
1 2 3 4 5 6
Chapter 49: How to Dynamically Modify Forms Using Form Events | 177
You might wonder, now that you have access to the User (through the security context), 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
// src/Acme/DemoBundle/FormType/FriendMessageFormType.php
use Symfony\Component\Security\Core\SecurityContext; use Doctrine\ORM\EntityRepository; // ... class FriendMessageFormType extends AbstractType { private $securityContext; public function __construct(SecurityContext $securityContext) { $this->securityContext = $securityContext; } public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('subject', 'text') ->add('body', 'textarea') ;
// grab the user, do a quick sanity check that one exists $user = $this->securityContext->getToken()->getUser(); if (!$user) { throw new \LogicException( 'The FriendMessageFormType cannot be used without an authenticated user!' ); }
$builder->addEventListener( FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($user) { $form = $event->getForm(); $formOptions = array( 'class' => 'Acme\DemoBundle\Entity\User', 'property' => 'fullName', 'query_builder' => function(EntityRepository $er) use ($user) { // build a custom query // return $er->createQueryBuilder('u')->addOrderBy('fullName',
'DESC'); // or call a method on your repository that returns the query builder // the $er is an instance of your UserRepository
Chapter 49: How to Dynamically Modify Forms Using Form Events | 178
47 48 49 50 51 52 53 54 55 56 57 }
// return $er->createOrderByFullNameQueryBuilder();
}, );
// create the field, this is similar the $builder->add() // field name, field type, data, options $form->add('friend', 'entity', $formOptions);
} ); }
// ...
The multiple and expanded form options will default to false because the type of the friend field is entity.
1 class FriendMessageController extends Controller 2 { 3 public function newAction(Request $request) 4 { 5 $securityContext = $this->container->get('security.context'); 6 $form = $this->createForm( 7 new FriendMessageFormType($securityContext) 8 ); 9 10 // ... 11 } 12 }
Chapter 49: How to Dynamically Modify Forms Using Form Events | 179
If you wish to create it from within a controller or any other service that has access to the form factory, you then use:
Listing 49-9
1 2 3 4 5 6 7 8 9 10 11
use Symfony\Component\DependencyInjection\ContainerAware; class FriendMessageController extends ContainerAware { public function newAction(Request $request) { $form = $this->get('form.factory')->create('acme_friend_message');
// ...
} }
1 $form = $this->createForm('acme_friend_message');
You can also easily embed the form type into another form:
Listing 49-11
1 2 3 4 5
// inside some other "form type" class public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('message', 'acme_friend_message'); }
1 2 3 4 5 6 7 8 9 10 11 12 13
Chapter 49: How to Dynamically Modify Forms Using Form Events | 180
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 }
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 added in Symfony 2.3. Before, they were named PRE_BIND, BIND and POST_BIND.
New in version 2.2.6: The behavior of the POST_SUBMIT event changed slightly in 2.2.6, which the below example uses.
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 49-13
1 2 3 4 5 6 7 8 9
Chapter 49: How to Dynamically Modify Forms Using Form Events | 181
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 }
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('sport', 'entity', array(...)) ; $formModifier = function(FormInterface $form, Sport $sport) { $positions = $sport->getAvailablePositions(); $form->add('position', 'entity', array('choices' => $positions)); }; $builder->addEventListener( FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($formModifier) { // this would be your entity, i.e. SportMeetup $data = $event->getData(); $formModifier($event->getForm(), $data->getSport()); } ); $builder->get('sport')->addEventListener( FormEvents::POST_SUBMIT, function(FormEvent $event) use ($formModifier) { // It's important here to fetch $event->getForm()->getData(), as // $event->getData() will get you the client data (that is, the ID) $sport = $event->getForm()->getData();
// 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 may still be 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. In that controller, you can submit your form, but instead of processing it, simply use the submitted form to render the updated fields. The response from the AJAX call can then be used to update the view.
Chapter 49: How to Dynamically Modify Forms Using Form Events | 182
Chapter 50
Let's start there: suppose that each Task belongs to multiple Tags objects. Start by creating a simple Task class:
Listing 50-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 }
public function setDescription($description) { $this->description = $description; } public function getTags() { 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 50-2
1 2 3 4 5 6 7
The name property is public here, but it can just as easily be protected or private (but then it would need getName and setName methods).
Now let's get to the forms. Create a form class so that a Tag object can be modified by the user:
Listing 50-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 }
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 50-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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class TaskController extends Controller { public function newAction(Request $request) { $task = new Task();
// dummy code - this is here just so that the Task has some tags // otherwise, this isn't an interesting example $tag1 = new Tag();
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 }
$tag1->name = 'tag1'; $task->getTags()->add($tag1); $tag2 = new Tag(); $tag2->name = '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('AcmeTaskBundle: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 50-6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
{# src/Acme/TaskBundle/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 level 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 4 5 6 7 8 9 10 11 12 13 14
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 50-8
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.
1. http://php.net/manual/en/function.ini-set.php
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 50-9
1 {{ form_widget(form.tags.vars.prototype.name)|e }}
On the rendered page, the result will look something like this:
Listing 50-10
1 <ul class="tags" data-prototype="<div><label class=" required">__name__</label><div id="task_tags___name__"><div><label for="task_tags___name___name" class=" required">Name</ label><input type="text" id="task_tags___name___name" name="task[tags][__name__][name]" required="required" maxlength="255" /></div></div></div>">
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 50-11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Get the ul that holds the collection of tags var collectionHolder = $('ul.tags'); // setup an "add a tag" link var $addTagLink = $('<a href="#" class="add_tag_link">Add a tag</a>'); var $newLinkLi = $('<li></li>').append($addTagLink);
jQuery(document).ready(function() { // add the "add a tag" anchor and li to the tags ul 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();
// add a new tag form (see next code block) addTagForm(collectionHolder, $newLinkLi);
}); });
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 50-12
1 function addTagForm(collectionHolder, $newLinkLi) { 2 // Get the data-prototype explained earlier 3 var prototype = collectionHolder.data('prototype'); 4 5 // get the new index 6 var index = collectionHolder.data('index'); 7 8 // Replace '__name__' in the prototype's HTML to 9 // instead be a number based on how many items we have 10 var newForm = prototype.replace(/__name__/g, index); 11 12 // increase the index with one for the next item 13 collectionHolder.data('index', index + 1); 14 15 // Display the form in the page in an li, before the "Add a tag" link li 16 var $newFormLi = $('<li></li>').append(newForm); 17 $newLinkLi.before($newFormLi); 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. To make handling these new tags easier, add an "adder" and a "remover" method for the tags in the Task class:
Listing 50-13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Next, add a by_reference option to the tags field and set it to false:
Listing 50-14
1 2 3 4 5
6 7 8 9 10 11 12 }
// ...
$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 we talk about next!).
If no addTag and removeTag method is found, the form will still use setTag even if by_reference is false. You'll learn more about the removeTag method later in this article.
1 2 3 4 5 6 7 8
A second potential issue deals with the Owning Side and Inverse Side2 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 50-16
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
If you have a OneToMany relationship, then the workaround is similar, except that you can simply call setTask from inside addTag.
2. http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html
1 2 3 4 5 6 7 8 9 10 11 12
Now, you need to put some code into the removeTag method of Task:
Listing 50-19
1 2 3 4 5 6 7 8 9 10 11 12
Templates 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 50-20
1 jQuery(document).ready(function() { 2 // add a delete link to all of the existing tag form li elements 3 collectionHolder.find('li').each(function() { 4 addTagFormDeleteLink($(this)); 5 }); 6 7 // ... the rest of the block from above 8 }); 9 10 function addTagForm() { 11 // ... 12 13 // add a delete link to the new form
14 15 }
addTagFormDeleteLink($newFormLi);
1 function addTagFormDeleteLink($tagFormLi) { 2 var $removeFormA = $('<a href="#">delete this tag</a>'); 3 $tagFormLi.append($removeFormA); 4 5 $removeFormA.on('click', function(e) { 6 // prevent the link from creating a "#" on the URL 7 e.preventDefault(); 8 9 // remove the li for the tag form 10 $tagFormLi.remove(); 11 }); 12 }
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
// src/Acme/TaskBundle/Controller/TaskController.php // ... public function editAction($id, Request $request) { $em = $this->getDoctrine()->getManager(); $task = $em->getRepository('AcmeTaskBundle:Task')->find($id);
if (!$task) { throw $this->createNotFoundException('No task found for is '.$id); } $originalTags = array();
// Create an array of the current Tag objects in the database foreach ($task->getTags() as $tag) { $originalTags[] = $tag; }
$editForm = $this->createForm(new TaskType(), $task); $editForm->handleRequest($request); if ($editForm->isValid()) {
// filter $originalTags to contain tags no longer present foreach ($task->getTags() as $tag) { foreach ($originalTags as $key => $toDel) { if ($toDel->getId() === $tag->getId()) { unset($originalTags[$key]); } } } // remove the relationship between the tag and the Task foreach ($originalTags as $tag) { // remove the Task from the Tag $tag->getTasks()->removeElement($task); // if it were a ManyToOne relationship, remove the relationship like this // $tag->setTask(null);
$em->persist($tag);
// if you wanted to delete the Tag entirely, you can also do that
46 47 48 49 50 51 52 53 54 55 56 57 }
// $em->remove($tag);
} $em->persist($task); $em->flush();
// redirect back to some edit page return $this->redirect($this->generateUrl('task_edit', array('id' => $id)));
}
As you can see, adding and removing the elements correctly can be tricky. Unless you have a ManyToMany 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 51
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1. http://api.symfony.com/2.3/Symfony/Component/Form/AbstractType.html
21 22 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. setDefaultOptions() - 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.
2. https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php 3. https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php
1 {# src/Acme/DemoBundle/Resources/views/Form/fields.html.twig #} 2 {% block gender_widget %} 3 {% spaceless %} 4 {% if expanded %} 5 <ul {{ block('widget_container_attributes') }}> 6 {% for child in form %} 7 <li> 8 {{ form_widget(child) }} 9 {{ form_label(child) }} 10 </li> 11 {% endfor %} 12 </ul> 13 {% else %} 14 {# just let the choice widget render the select tag #} 15 {{ block('choice_widget') }} 16 {% endif %} 17 {% endspaceless %} 18 {% 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.
Listing 51-3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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.
PDF brought to you by generated on November 10, 2013 Chapter 51: How to Create a Custom Form Field Type | 198
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 51-6
1 # src/Acme/DemoBundle/Resources/config/services.yml 2 services: 3 acme_demo.form.type.gender: 4 class: Acme\DemoBundle\Form\Type\GenderType 5 arguments: 6 - "%genders%" 7 tags: 8 - { name: form.type, alias: 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 51-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 }
// ...
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 51-8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// ...
class AuthorType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('gender_code', 'gender', array( 'empty_value' => '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 52
Listing 52-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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() setDefaultOptions() finishView()
For more information on what those methods do, you can refer to the Creating Custom Field Types cookbook article.
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 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
/** * @var string The path - typically stored in the database */ private $path; /** * @var \Symfony\Component\HttpFoundation\File\UploadedFile * @Assert\File(maxSize="2M") */ public $file; // ... /** * 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 setDefaultOptions method in order to add an image_path option; 2. Override the buildForm and 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 52-4
1 2 3 4 5 6 7 8
9 10 class ImageTypeExtension extends AbstractTypeExtension 11 { 12 /** 13 * Returns the name of the type being extended. 14 * 15 * @return string The name of the type being extended 16 */ 17 public function getExtendedType() 18 { 19 return 'file'; 20 } 21 22 /** 23 * Add the image_path option 24 * 25 * @param OptionsResolverInterface $resolver 26 */ 27 public function setDefaultOptions(OptionsResolverInterface $resolver) 28 { 29 $resolver->setOptional(array('image_path')); 30 } 31 32 /** 33 * Pass the image url to the view 34 * 35 * @param FormView $view 36 * @param FormInterface $form 37 * @param array $options 38 */ 39 public function buildView(FormView $view, FormInterface $form, array $options) 40 { 41 if (array_key_exists('image_path', $options)) { 42 $parentData = $form->getParent()->getData(); 43 44 if (null !== $parentData) { 45 $accessor = PropertyAccess::createPropertyAccessor(); 46 $imageUrl = $accessor->getValue($parentData, $options['image_path']); 47 } else { 48 $imageUrl = null; 49 } 50 51 // set an "image_url" variable that will be available when rendering this field 52 $view->vars['image_url'] = $imageUrl; 53 } 54 } 55 56 }
Listing 52-5
1 2 3 4 5 6 7 8 9 10 11 12 13
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
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 53
New in version 2.3: This inherit_data option was known as virtual before Symfony 2.3.
The inherit_data form field option can be very useful when you have some duplicated fields in different entities. For example, imagine you have two entities, a Company and a Customer:
Listing 53-1
1 2 3 4 5 6 7 8 9 10 11 12 13
Listing 53-2
1 2 3 4 5 6 7 8
9 10 11 12 13 }
As you can see, each entity shares a few of the same fields: address, zipcode, city, country. Let's build two forms for these entities, CompanyType and CustomerType:
Listing 53-3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Listing 53-4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Instead of including the duplicated fields address, zipcode, city and country in both of these forms, we will create a third form for that. We will call this form simply LocationType:
Listing 53-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 }
->add('address', 'textarea') ->add('zipcode', 'text') ->add('city', 'text') ->add('country', 'text'); } public function setDefaultOptions(OptionsResolverInterface $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 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().
Let's make this work by adding the location form to our two original forms:
Listing 53-6
1 2 3 4 5 6 7 8 9
Listing 53-7
1 2 3 4 5 6 7 8 9
That's it! You have extracted duplicated field definitions to a separate location form that you can reuse wherever you need it.
Chapter 54
The Basics
The simplest TypeTestCase implementation looks like the following:
Listing 54-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 }
public function testSubmitValidData() { $formData = array( 'test' => 'test', 'test2' => 'test2', ); $type = new TestedType(); $form = $this->factory->create($type); $object = new TestObject(); $object->fromArray($formData);
So, what does it test? Let's explain it line by line. First you verify if the FormType compiles. This includes basic class inheritance, the buildForm function and options resolution. This should be the first test you write:
Listing 54-2
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 54-3
1 $form->submit($formData); 2 $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 54-4
1 $this->assertEquals($object, $form->getData());
5. http://api.symfony.com/2.3/Symfony/Component/Form/FormInterface.html#isSynchronized()
Finally, check the creation of the FormView. You should check if all widgets you want to display are available in the children property:
Listing 54-5
1 2 3 4 5 6
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 PreloadedExtension class:
Listing 54-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
class TestedTypeTest extends TypeTestCase { protected function getExtensions() { $childType = new TestChildType(); return array(new PreloadedExtension(array( $childType->getName() => $childType, ), array())); } public function testSubmitValidData() { $type = new TestedType(); $form = $this->factory->create($type);
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 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
class TestedTypeTest extends TypeTestCase { protected function setUp() { parent::setUp(); $this->factory = Forms::createFormFactoryBuilder() ->addExtensions($this->getExtensions()) ->addTypeExtension( new FormTypeValidatorExtension( $this->getMock('Symfony\Component\Validator\ValidatorInterface') ) ) ->addTypeGuesser( $this->getMockBuilder( 'Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser' ) ->disableOriginalConstructor() ->getMock() ) ->getFormFactory(); $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory); }
6. http://www.phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers
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
use Acme\TestBundle\Form\Type\TestedType; use Acme\TestBundle\Model\TestObject; use Symfony\Component\Form\Test\TypeTestCase; class TestedTypeTest extends TypeTestCase {
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 55
1 public function indexAction() 2 { 3 $blog = ...; 4 5 // $blog is passed in as the data, so the empty_data option is not needed 6 $form = $this->createForm(new BlogType(), $blog); 7 8 // no data is passed in, so empty_data is used to get the "starting data" 9 $form = $this->createForm(new BlogType()); 10 }
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
Chapter 55: How to configure Empty Data for a Form Class | 214
8 class BlogType extends AbstractType 9 { 10 private $someDependency; 11 12 public function __construct($someDependency) 13 { 14 $this->someDependency = $someDependency; 15 } 16 // ... 17 18 public function setDefaultOptions(OptionsResolverInterface $resolver) 19 { 20 $resolver->setDefaults(array( 21 'empty_data' => new Blog($this->someDependency), 22 )); 23 } 24 }
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\OptionsResolverInterface; use Symfony\Component\Form\FormInterface; // ... public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'empty_data' => function (FormInterface $form) { return new Blog($form->get('title')->getData()); }, )); }
Chapter 55: How to configure Empty Data for a Form Class | 215
Chapter 56
New in version 2.3: The handleRequest() method was added in Symfony 2.3.
In Symfony 2.3, a new handleRequest()1 method was added, which makes handling form submissions easier than ever:
Listing 56-1
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->redirect($this->generateUrl('task_success')); } return $this->render('AcmeTaskBundle:Default:new.html.twig', array( 'form' => $form->createView(), )); }
1. http://api.symfony.com/2.3/SymfonyComponentFormFormInterface.html#handleRequest()
Chapter 56: How to use the submit() Function to handle Form Submissions | 216
In some cases, you want better control over when exactly your form is submitted and what data is passed to it. Instead of using the handleRequest()2 method, pass the submitted data directly to submit()3:
Listing 56-2
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->redirect($this->generateUrl('task_success')); } } return $this->render('AcmeTaskBundle:Default:new.html.twig', array( 'form' => $form->createView(), )); }
Forms consisting of nested fields expect an array in submit()4. You can also submit individual fields by calling submit()5 directly on the field:
Listing 56-3
1 $form->get('firstName')->submit('Fabien');
Chapter 56: How to use the submit() Function to handle Form Submissions | 217
Before Symfony 2.3, the submit()6 method accepted a Request7 object as a convenient shortcut to the previous example:
Listing 56-4
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); if ($form->isValid()) { // perform some action... return $this->redirect($this->generateUrl('task_success')); } } return $this->render('AcmeTaskBundle:Default:new.html.twig', array( 'form' => $form->createView(), )); }
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.
Chapter 56: How to use the submit() Function to handle Form Submissions | 218
Chapter 57
Chapter 57: How to use the Virtual Form Field Option | 219
Chapter 58
Usage
To log a message simply get the logger service from the container in your controller:
Listing 58-1
1 public function indexAction() 2 { 3 $logger = $this->get('logger'); 4 $logger->info('I just got the logger'); 5 $logger->error('An error occurred'); 6 7 // ... 8 }
The logger service has different methods for different logging levels. See LoggerInterface2 for details on which methods are available.
1. https://github.com/Seldaek/monolog 2. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Log/LoggerInterface.html
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). 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 standard edition) by forwarding the messages to another handler.
1 # app/config/config.yml 2 monolog: 3 handlers: 4 applog: 5 type: stream 6 path: /var/log/symfony.log 7 level: error 8 main: 9 type: fingers_crossed 10 action_level: warning 11 handler: file 12 file: 13 type: stream 14 level: debug 15 syslog: 16 type: syslog 17 level: error
The above configuration defines a stack of handlers which will be called in the order where 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.
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 23 24 25 26 27 28 29
namespace Acme\MyBundle; 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; } }
Listing 58-5
1 # app/config/config.yml 2 services: 3 monolog.formatter.session_request: 4 class: Monolog\Formatter\LineFormatter 5 arguments: 6 - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%%\n"
7 8 monolog.processor.session_request: 9 class: Acme\MyBundle\SessionRequestProcessor 10 arguments: ["@session"] 11 tags: 12 - { name: monolog.processor, method: processRecord } 13 14 monolog: 15 handlers: 16 main: 17 type: stream 18 path: "%kernel.logs_dir%/%kernel.environment%.log" 19 level: debug 20 formatter: monolog.formatter.session_request
If you use several handlers, you can also register the processor at the handler level instead of globally.
Chapter 59
1 # app/config/config_prod.yml 2 monolog: 3 handlers: 4 mail: 5 type: fingers_crossed 6 action_level: critical 7 handler: buffered 8 buffered: 9 type: buffer 10 handler: swift 11 swift: 12 type: swift_mailer 13 from_email: [email protected] 14 to_email: [email protected] 15 subject: An Error Occurred! 16 level: debug
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. It then logs everything including messages below the action level. The critical level is only triggered for 5xx HTTP code errors. The handler setting means that the output is then passed onto the buffered handler.
If you want both 400 level and 500 level errors to trigger an email, set the action_level to error instead of critical.
The buffered handler simply keeps all the messages for a request and then passes them onto the nested handler in one go. If you do not use this handler then each message will be emailed separately. This is
1. https://github.com/Seldaek/monolog
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 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:
The default spool setting for swiftmailer is set to memory, which means that emails are sent at the very end of the request. However, this does not work with buffered logs at the moment. In order to enable emailing logs per the example below, you must comment out the spool: { type: memory } line in the config.yml file.
Listing 59-2
1 # app/config/config_prod.yml 2 monolog: 3 handlers: 4 main: 5 type: fingers_crossed 6 action_level: critical 7 handler: grouped 8 grouped: 9 type: group 10 members: [streamed, buffered] 11 streamed: 12 type: stream 13 path: "%kernel.logs_dir%/%kernel.environment%.log" 14 level: debug 15 buffered: 16 type: buffer 17 handler: swift 18 swift: 19 type: swift_mailer 20 from_email: [email protected] 21 to_email: [email protected] 22 subject: An Error Occurred! 23 level: debug
This uses the group handler to send the messages to the two group members, the buffered and the stream handlers. The messages will now be both written to the log file and emailed.
Chapter 60
1 monolog: 2 handlers: 3 main: 4 type: stream 5 path: /var/log/symfony.log 6 channels: !doctrine 7 doctrine: 8 type: stream 9 path: /var/log/doctrine.log 10 channels: doctrine
Yaml specification
You can specify the configuration by many forms:
Listing 60-2
1 channels: ~ # Include all the channels 2 3 channels: foo # Include only channel "foo" 4 channels: !foo # Include all channels, except "foo"
5 6 7 8 9 10 11 12 13 14
channels: [foo, bar] # Include only channels "foo" and "bar" channels: [!foo, !bar] # Include all channels, except "foo" and "bar" channels: type: elements: channels: type: elements: inclusive # Include only those listed below [ foo, bar ] exclusive # Include all, except those listed below [ foo, bar ]
Chapter 61
1 interface DataCollectorInterface 2 { 3 /** 4 * Collects data for the given Request and Response. 5 * 6 * @param Request $request A Request instance 7 * @param Response $response A Response instance 8 * @param \Exception $exception An Exception instance 9 */ 10 function collect(Request $request, Response $response, \Exception $exception = null); 11 12 /** 13 * Returns the name of the collector. 14 * 15 * @return string The collector name 16 */ 17 function getName(); 18 }
The getName() method must return a unique name. This is used to access the information later on (see How to use the Profiler in a Functional Test for instance). The collect() method is responsible for storing the data it wants to give access to in local properties.
1. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/DataCollector/DataCollectorInterface.html
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.
Most of the time, it is convenient to extend DataCollector2 and populate the $this->data property (it takes care of serializing the $this->data property):
Listing 61-2
1 class MemoryDataCollector extends DataCollector 2 { 3 public function collect(Request $request, Response $response, \Exception $exception = 4 null) 5 { 6 $this->data = array( 7 'memory' => memory_get_peak_usage(true), 8 ); 9 } 10 11 public function getMemory() 12 { 13 return $this->data['memory']; 14 } 15 16 public function getName() 17 { 18 return 'memory'; 19 } }
1 {% extends 'WebProfilerBundle:Profiler:layout.html.twig' %} 2 3 {% block toolbar %} 4 {# the web debug toolbar content #} 5 {% endblock %}
2. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/DataCollector/DataCollector.html
6 7 8 9 10 11 12 13 14 15 16 17
{% block head %} {# if the web profiler panel needs some specific JS or CSS files #} {% endblock %} {% block menu %} {# the menu content #} {% endblock %} {% block panel %} {# the panel content #} {% endblock %}
Each block is optional. The toolbar block is used for the web debug toolbar and menu and panel are used to add a panel to the web profiler. All blocks have access to the collector object.
Built-in templates use a base64 encoded image for the toolbar (<img src="data:image/ png;base64,..."). You can easily calculate the base64 value for an image with this little script: echo base64_encode(file_get_contents($_SERVER['argv'][1]));.
To enable the template, add a template attribute to the data_collector tag in your configuration. For example, assuming your template is in some AcmeDebugBundle:
Listing 61-5
1 services: 2 data_collector.your_collector_name: 3 class: Acme\DebugBundle\Collector\Class\Name 4 tags: 5 - { name: data_collector, template: "AcmeDebugBundle:Collector:templatename", id: "your_collector_name" }
Chapter 62
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 /admin/ urls.
1. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RequestMatcher.html 2. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RequestMatcherInterface.html
Chapter 62: How to use Matchers to enable the Profiler Conditionally | 231
interface requires one method: matches()3. This method returns false to disable the profiler and true to enable the profiler. To enable the profiler when a ROLE_SUPER_ADMIN is logged in, you can use something like:
Listing 62-2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Now the service is registered, the only thing left to do is configure the profiler to use this service as the matcher:
Listing 62-4
3. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RequestMatcherInterface.html#matches()
Chapter 62: How to use Matchers to enable the Profiler Conditionally | 232
Chapter 63
1 2 3 4 5 6 7 8 9 10 11 12 13
1. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html#getRequestFormat()
Chapter 63: How to register a new Request Format and Mime Type | 233
1 # app/config/config.yml 2 services: 3 acme.demobundle.listener.request: 4 class: Acme\DemoBundle\RequestListener 5 tags: 6 - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
At this point, the acme.demobundle.listener.request service has been configured and will be notified when the Symfony kernel dispatches the kernel.request event.
You can also register the listener in a configuration extension class (see Importing Configuration via Container Extensions for more information).
Chapter 63: How to register a new Request Format and Mime Type | 234
Chapter 64
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 64-2
1 2 3 4 5 6 7
{# If the current scheme is HTTPS #} {{ path('secure') }} {# generates /secure #} {# If the current scheme is HTTP #} {{ path('secure') }} {# generates https://example.com/secure #}
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.
Chapter 64: How to force routes to always use HTTPS or HTTP | 235
Chapter 65
That's it! Now, the {name} parameter can contain the / character.
Chapter 66
1 AppBundle: 2 resource: "@App/Controller/" 3 type: annotation 4 prefix: /app 5 6 root: 7 path: / 8 defaults: 9 _controller: FrameworkBundle:Redirect:urlRedirect 10 path: /app 11 permanent: true
In this example, you configure a route for the / path and let RedirectController1 handle it. This controller comes standard with Symfony and offers two actions for redirecting request: urlRedirect redirects to another path. You must provide the path parameter containing the path of the resource you want to redirect to. redirect (not shown here) redirects to another route. You must provide the route parameter with the name of the route you want to redirect to. The permanent switch tells both methods to issue a 301 HTTP status code instead of the default 302 status code.
1. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.html
Chapter 66: How to configure a redirect to another route without a custom controller | 237
Chapter 67
1 blog_show: 2 path: 3 defaults: 4 methods: 5 6 blog_update: 7 path: 8 defaults: 9 methods: 10 11 blog_delete: 12 path: 13 defaults: 14 methods:
/blog/{slug} { _controller: AcmeDemoBundle:Blog:show } [GET] /blog/{slug} { _controller: AcmeDemoBundle:Blog:update } [PUT] /blog/{slug} { _controller: AcmeDemoBundle:Blog:delete } [DELETE]
Chapter 67: How to use HTTP Methods beyond GET and POST in Routes | 238
Unfortunately, life isn't quite this simple, since most browsers do not support sending PUT and DELETE requests. Fortunately Symfony2 provides you with a simple way of working around this limitation. By including a _method parameter in the query string or parameters of an HTTP request, Symfony2 will use this as the method when matching routes. Forms automatically include a hidden field for this parameter if their submission method is not GET or POST. See the related chapter in the forms documentation for more information.
1. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html#enableHttpMethodParameterOverride()
Chapter 67: How to use HTTP Methods beyond GET and POST in Routes | 239
Chapter 68
You can now control and set the acme_demo.locales parameter somewhere in your container:
Listing 68-2
You can also use a parameter to define your route path (or part of your path):
Listing 68-3
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 68: How to use Service Container Parameters in your Routes | 240
Chapter 69
Loading Routes
The routes in a Symfony application are loaded by the DelegatingLoader5. 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 LoaderInterface6 and therefore have two important methods: supports()7 and load()8. Take these lines from the routing.yml in the AcmeDemoBundle of the Standard Edition:
Listing 69-1
1. 2. 3. 4. 5.
When the main loader parses this, it tries all the delegate loaders and calls their supports()9 method with the given resource (@AcmeDemoBundle/Controller/DemoController.php) and type (annotation) as arguments. When one of the loader returns true, its load()10 method will be called, which should return a RouteCollection11 containing Route12 objects.
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 Acme\DemoBundle\Routing; use use use use Symfony\Component\Config\Loader\LoaderInterface; Symfony\Component\Config\Loader\LoaderResolverInterface; Symfony\Component\Routing\Route; Symfony\Component\Routing\RouteCollection;
class ExtraLoader implements LoaderInterface { 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();
// prepare a new route $pattern = '/extra/{parameter}'; $defaults = array( '_controller' => 'AcmeDemoBundle:Demo:extra', ); $requirements = array( 'parameter' => '\d+', ); $route = new Route($pattern, $defaults, $requirements); // add the new route to the route collection:
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 }
$routeName = 'extraRoute'; $routes->add($routeName, $route); $this->loaded = true; return $routes; } public function supports($resource, $type = null) { return 'extra' === $type; } public function getResolver() { // needed, but can be blank, unless you want to load other resources // and if you do, using the Loader base class is easier (see below) } public function setResolver(LoaderResolverInterface $resolver) { // same as above }
Notice the tag routing.loader. All services with this tag will be marked as potential route loaders and added as specialized routers to the DelegatingLoader14.
The important part here is the type key. Its value should be "extra". This is the type which our ExtraLoader supports and this will make sure its load() method gets called. The resource key is insignificant for the ExtraLoader, so we set it to ".".
14. http://api.symfony.com/2.3/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.html
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
namespace Acme\DemoBundle\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 = '@AcmeDemoBundle/Resources/config/import_routing.yml'; $type = 'yaml'; $importedRoutes = $this->import($resource, $type); $collection->addCollection($importedRoutes); return $collection; } public function supports($resource, $type = null) { return $type === 'advanced_extra'; } }
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.).
15. http://api.symfony.com/2.3/Symfony/Component/Config/Loader/LoaderInterface.html 16. http://api.symfony.com/2.3/Symfony/Component/Config/Loader/Loader.html 17. http://api.symfony.com/2.3/Symfony/Component/Config/Loader/LoaderResolver.html 18. http://api.symfony.com/2.3/Symfony/Component/Config/Loader/LoaderInterface.html#supports() 19. http://api.symfony.com/2.3/Symfony/Component/Config/Loader/LoaderInterface.html#load() 20. http://api.symfony.com/2.3/Symfony/Component/Config/Loader/Loader.html#import()
Chapter 70
How to load Security Users from the Database (the Entity Provider)
The security layer is one of the smartest tools of Symfony. It handles two things: the authentication and the authorization processes. Although it may seem difficult to understand how it works internally, the security system is very flexible and allows you to integrate your application with any authentication backend, like Active Directory, an OAuth server or a database.
Introduction
This article focuses on how to authenticate users against a database table managed by a Doctrine entity class. The content of this cookbook entry is split in three parts. The first part is about designing a Doctrine User entity class and making it usable in the security layer of Symfony. The second part describes how to easily authenticate a user with the Doctrine EntityUserProvider1 object bundled with the framework and some configuration. Finally, the tutorial will demonstrate how to create a custom EntityUserProvider2 object to retrieve users from a database with custom conditions. This tutorial assumes there is a bootstrapped and loaded Acme\UserBundle bundle in the application kernel.
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 245
Listing 70-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
/** * Acme\UserBundle\Entity\User * * @ORM\Table(name="acme_users") * @ORM\Entity(repositoryClass="Acme\UserBundle\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=32) */ private $salt; /** * @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; $this->salt = md5(uniqid(null, true)); }
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 246
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 }
/** * @inheritDoc */ public function getUsername() { return $this->username; } /** * @inheritDoc */ public function getSalt() { return $this->salt; } /** * @inheritDoc */ public function getPassword() { return $this->password; } /** * @inheritDoc */ public function getRoles() { return array('ROLE_USER'); } /** * @inheritDoc */ public function eraseCredentials() { } /** * @see \Serializable::serialize() */ public function serialize() { return serialize(array( $this->id, )); } /** * @see \Serializable::unserialize() */ public function unserialize($serialized) { list ( $this->id, ) = unserialize($serialized); }
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 247
In order to use an instance of the AcmeUserBundle:User class in the Symfony security layer, the entity class must implement the UserInterface4. This interface forces the class to implement the five following methods: getRoles(), getPassword(), getSalt(), getUsername(), eraseCredentials()
Below is an export of the User table from MySQL with user admin and password admin (which has been encoded). For details on how to create user records and encode their password, see Encoding the User's Password.
Listing 70-4
1 2 3 4 5 6
$ mysql> select * from acme_users; +----+----------+------+------------------------------------------+--------------------+-----------+ | id | username | salt | password | email | is_active | +----+----------+------+------------------------------------------+--------------------+-----------+ | 1 | admin | | d033e22ae348aeb5660fc2140aec35850c4da997 | [email protected] | 1 | +----+----------+------+------------------------------------------+--------------------+-----------+
The next part will focus on how to authenticate one of these users thanks to the Doctrine entity user provider and a couple of lines of configuration.
1 # app/config/security.yml 2 security:
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 248
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
encoders: Acme\UserBundle\Entity\User: algorithm: sha1 encode_as_base64: false iterations: 1 role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ] providers: administrators: entity: { class: AcmeUserBundle:User, property: username } firewalls: admin_area: pattern: ^/admin http_basic: ~ access_control: - { path: ^/admin, roles: ROLE_ADMIN }
The encoders section associates the sha1 password encoder to the entity class. This means that Symfony will expect the password that's stored in the database to be encoded using this algorithm. For details on how to create a new User object with a properly encoded password, see the Encoding the User's Password section of the security chapter. The providers section defines an administrators user provider. A user provider is a "source" of where users are loaded during authentication. In this case, the entity keyword means that Symfony will use the Doctrine entity user provider to load User entity objects from the database by using the username unique field. In other words, this tells Symfony how to fetch the user from the database before checking the password validity.
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 249
For this example, the first three methods will return true whereas the isEnabled() method will return the boolean value in the isActive field.
Listing 70-6
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
Now, if you try to authenticate as a user who's is_active database field is set to 0, you won't be allowed. The next session will focus on how to write a custom entity provider to authenticate a user with his username or his email address.
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 250
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
class UserRepository extends EntityRepository implements UserProviderInterface { public function loadUserByUsername($username) { $q = $this ->createQueryBuilder('u') ->where('u.username = :username OR u.email = :email') ->setParameter('username', $username) ->setParameter('email', $username) ->getQuery(); try { // The Query::getSingleResult() method throws an exception // if there is no record matching the criteria. $user = $q->getSingleResult(); } catch (NoResultException $e) { $message = sprintf( 'Unable to find an active admin AcmeUserBundle:User object identified by "%s".', $username ); throw new UsernameNotFoundException($message, 0, $e); } return $user; } 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()); } }
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 251
To finish the implementation, the configuration of the security layer must be changed to tell Symfony to use the new custom entity provider instead of the generic Doctrine entity provider. It's trivial to achieve by removing the property field in the security.providers.administrators.entity section of the security.yml file.
Listing 70-8
By doing this, the security layer will use an instance of UserRepository and call its loadUserByUsername() method to fetch a user from the database whether he filled in his username or email address.
In this example, the AcmeUserBundle:User entity class defines a many-to-many relationship with a AcmeUserBundle:Role entity class. A user can be related to several roles and a role can be composed of one or more users. The previous getRoles() method now returns the list of related roles. Notice that __construct() and getRoles() methods have changed:
Listing 70-9
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 252
21 22 23 24 25 26 27 28 29 }
// ...
The AcmeUserBundle:Role entity class defines three fields (id, name and role). The unique role field contains the role name (e.g. ROLE_ADMIN) used by the Symfony security layer to secure parts of the application:
Listing 70-10
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
/** * @ORM\Table(name="acme_roles") * @ORM\Entity() */ class Role implements RoleInterface { /** * @ORM\Column(name="id", type="integer") * @ORM\Id() * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(name="name", type="string", length=30) */ private $name; /** * @ORM\Column(name="role", type="string", length=20, unique=true) */ private $role; /** * @ORM\ManyToMany(targetEntity="User", mappedBy="roles") */ private $users;
public function __construct() { $this->users = new ArrayCollection(); }
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 253
45 46 47 48 49 50 }
{ return $this->role; }
For brevity, the getter and setter methods are hidden, but you can generate them:
Listing 70-11
This will create the acme_role table and a user_role that stores the many-to-many relationship between acme_user and acme_role. If you had one user linked to one role, your database might look something like this:
Listing 70-13
1 2 3 4 5 6 7 8 9 10 11 12 13
$ mysql> select * from acme_role; +----+-------+------------+ | id | name | role | +----+-------+------------+ | 1 | admin | ROLE_ADMIN | +----+-------+------------+ mysql> select * from user_role; +---------+---------+ | user_id | role_id | +---------+---------+ | 1 | 1 | +---------+---------+
And that's it! When the user logs in, Symfony security system will call the User::getRoles method. This will return an array of Role objects that Symfony will use to determine if the user should have access to certain parts of the system.
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 254
Listing 70-14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// ...
}
// ...
}
The QueryBuilder::leftJoin() method joins and fetches related roles from the AcmeUserBundle:User model class when a user is retrieved with his email address or username.
Chapter 70: How to load Security Users from the Database (the Entity Provider) | 255
Chapter 71
1 # app/config/security.yml 2 firewalls: 3 main: 4 remember_me: 5 key: "%secret%" 6 lifetime: 31536000 # 365 days in seconds 7 path: / 8 domain: ~ # Defaults to the current domain from $_SERVER
It's a good idea to provide the user with the option to use or not use the remember me functionality, as it will not always be appropriate. The usual way of doing this is to add a checkbox to the login form. By giving the checkbox the name _remember_me, the cookie will automatically be set when the checkbox is checked and the user successfully logs in. So, your specific login form might ultimately look like this:
Listing 71-2
1 2 3 4 5 6 7 8 9 10
type="password" id="password" name="_password" /> type="checkbox" id="remember_me" name="_remember_me" checked /> for="remember_me">Keep me logged in</label> type="submit" name="login" />
The user will then automatically be logged in on subsequent visits while the cookie remains valid.
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 71-3
1 2 3 4 5 6 7 8 9
10 11 12 13 }
// ...
You can also choose to install and use the optional JMSSecurityExtraBundle1, which can secure your controller using annotations:
Listing 71-4
1 2 3 4 5 6 7 8 9
use JMS\SecurityExtraBundle\Annotation\Secure;
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 his 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, he will be able to access every account page - except for the edit page - without being forced to re-authenticate. However, when he tries to access the editAction controller, he will be forced to reauthenticate, since he is 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.
1. https://github.com/schmittjoh/JMSSecurityExtraBundle
Chapter 72
1 interface VoterInterface 2 { 3 public function supportsAttribute($attribute); 4 public function supportsClass($class); 5 public function vote(TokenInterface $token, $object, array $attributes); 6 }
The supportsAttribute() method is used to check if the voter supports the given user attribute (i.e: a role, an acl, etc.). The supportsClass() method is used to check if the voter supports the current user token class. The vote() method must implement the business logic that verifies whether or not the user is granted access. This method must return one of the following values: VoterInterface::ACCESS_GRANTED: The user is allowed to access the application VoterInterface::ACCESS_ABSTAIN: The voter cannot decide if the user is granted or not VoterInterface::ACCESS_DENIED: The user is not allowed to access the application
1. http://api.symfony.com/2.3/Symfony/Component/Security/Core/Authorization/Voter/VoterInterface.html
Chapter 72: How to implement your own Voter to blacklist IP Addresses | 259
In this example, you'll check if the user's IP address matches against a list of blacklisted addresses. If the user's IP is blacklisted, you'll return VoterInterface::ACCESS_DENIED, otherwise you'll return VoterInterface::ACCESS_ABSTAIN as this voter's purpose is only to deny access, not to grant access.
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
That's it! The voter is done. The next step is to inject the voter into the security layer. This can be done easily through the service container.
Your implementation of the methods supportsAttribute()2 and supportsClass()3 are not being called internally by the framework. Once you have registered your voter the vote() method will always be called, regardless of whether or not these two methods return true. Therefore you need to call those methods in your implementation of the vote() method and return ACCESS_ABSTAIN if your voter does not support the class or attribute.
Chapter 72: How to implement your own Voter to blacklist IP Addresses | 260
1 # src/Acme/AcmeBundle/Resources/config/services.yml 2 services: 3 security.access.blacklist_voter: 4 class: Acme\DemoBundle\Security\Authorization\Voter\ClientIpVoter 5 arguments: ["@service_container", [123.123.123.123, 171.171.171.171]] 6 public: false 7 tags: 8 - { name: security.voter }
Be sure to import this configuration file from your main application configuration file (e.g. app/ config/config.yml). For more information see Importing Configuration with imports. To read more about defining services in general, see the Service Container chapter.
1 # app/config/security.yml 2 security: 3 access_decision_manager: 4 # strategy can be: affirmative, unanimous or consensus 5 strategy: unanimous
That's it! Now, when deciding whether or not a user should have access, the new voter will deny access to any user in the list of blacklisted IPs.
For a more advanced usage see Access Decision Manager.
2. http://api.symfony.com/2.3/Symfony/Component/Security/Core/Authorization/Voter/VoterInterface.html#supportsAttribute() 3. http://api.symfony.com/2.3/Symfony/Component/Security/Core/Authorization/Voter/VoterInterface.html#supportsClass()
Chapter 72: How to implement your own Voter to blacklist IP Addresses | 261
Chapter 73
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 his 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 Symfony2, 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 73-1
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 73-2
Getting Started
Coming back to the small example from the beginning, let's implement ACL for it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
class BlogController { // ... public function addCommentAction(Post $post) { $comment = new Comment();
1. https://github.com/IamPersistent/MongoDBAclBundle
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 }
// creating the ACL $aclProvider = $this->get('security.acl.provider'); $objectIdentity = ObjectIdentity::fromDomainObject($comment); $acl = $aclProvider->createAcl($objectIdentity); // retrieving the security identity of the currently logged-in user $securityContext = $this->get('security.context'); $user = $securityContext->getToken()->getUser(); $securityIdentity = UserSecurityIdentity::fromAccount($user); // grant owner access $acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER); $aclProvider->updateAcl($acl);
} }
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 73-4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// src/Acme/DemoBundle/Controller/BlogController.php // ...
class BlogController { // ... public function editCommentAction(Comment $comment) { $securityContext = $this->get('security.context');
// check for edit access if (false === $securityContext->isGranted('EDIT', $comment)) { throw new AccessDeniedException(); }
17 18 19 20 }
In this example, you check whether the user has the EDIT permission. Internally, Symfony2 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 73-5
1 2 3 4 5 6 7 8
$builder = new MaskBuilder(); $builder ->add('view') ->add('edit') ->add('delete') ->add('undelete') ; $mask = $builder->get(); // int(29)
This integer bitmask can then be used to grant a user the base permissions you added above:
Listing 73-6
The user is now allowed to view, edit, delete, and un-delete objects.
Chapter 74
Design Concepts
Symfony2'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. Symfony2'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 Symfony2'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.
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.
Whether someone is allowed to EDIT, OPERATOR, MASTER, or make changes to the domain object. OWNER Whether someone is allowed to create the domain object. CREATE, OPERATOR, MASTER, or OWNER
Intended Meaning Whether someone is allowed to delete the domain object. Whether someone is allowed to restore a previously deleted domain object. Whether someone is allowed to perform all of the above actions. Whether someone is allowed to perform all of the above actions, and in addition is allowed to grant any of the above permissions to others. Whether someone owns the domain object. An owner can perform any of the above actions and grant master and owner permissions.
Integer Bitmasks DELETE, OPERATOR, MASTER, or OWNER UNDELETE, OPERATOR, MASTER, or OWNER OPERATOR, MASTER, or OWNER MASTER, or OWNER
OPERATOR MASTER
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.
1. https://github.com/schmittjoh/JMSSecurityExtraBundle
allows you to replace the way access decisions are reached without actually modifying the ACL class itself. The PermissionGrantingStrategy first checks all your object-scope ACEs if none is applicable, the classscope ACEs will be checked, if none is applicable, then the process will be repeated with the ACEs of the parent ACL. If no parent ACL exists, an exception will be thrown.
Chapter 75
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 75-2
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 75: How to force HTTPS or HTTP for Different URLs | 270
Chapter 76
Now, when no URL is set in the session, users will be sent to the default_security_target route.
true
1 2 3 4 5 6 7 8 9 10 11
12 13 <input type="hidden" name="_target_path" value="account" /> 14 15 <input type="submit" name="login" /> 16 </form>
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 76-5
Chapter 77
1 2 3 4 5 6 7 8 9 10 11
// ...
}
You can also secure any service in a similar way by injecting the security.context 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 77-2
1 2 3 4 5 6 7 8 9 10
Chapter 77: How to secure any Service or Method in your Application | 274
11 12 13 }
// ...
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.context service into the object. Since it won't make sense not to perform the security check, this is an ideal candidate for constructor injection, which guarantees that the security context object will be available inside the NewsletterManager class:
Listing 77-3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
namespace Acme\HelloBundle\Newsletter; use Symfony\Component\Security\Core\SecurityContextInterface; class NewsletterManager { protected $securityContext; public function __construct(SecurityContextInterface $securityContext) { $this->securityContext = $securityContext; }
// ...
}
1 # src/Acme/HelloBundle/Resources/config/services.yml 2 parameters: 3 newsletter_manager.class: Acme\HelloBundle\Newsletter\NewsletterManager 4 5 services: 6 newsletter_manager: 7 class: "%newsletter_manager.class%" 8 arguments: ["@security.context"]
The injected service can then be used to perform the security check when the sendNewsletter() method is called:
Listing 77-5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
namespace Acme\HelloBundle\Newsletter; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\SecurityContextInterface; // ... class NewsletterManager { protected $securityContext; public function __construct(SecurityContextInterface $securityContext) { $this->securityContext = $securityContext; } public function sendNewsletter() {
Chapter 77: How to secure any Service or Method in your Application | 275
18 19 20 21 22 23 24 25 26 }
// ...
}
// ...
If the current user does not have the ROLE_NEWSLETTER_ADMIN, they will be prompted to log in.
You can then achieve the same results as above using an annotation:
Listing 77-7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1. https://github.com/schmittjoh/JMSSecurityExtraBundle
Chapter 77: How to secure any Service or Method in your Application | 276
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.
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.
2. https://github.com/schmittjoh/JMSSecurityExtraBundle
Chapter 77: How to secure any Service or Method in your Application | 277
Chapter 78
1 2 3 4 5 6
7 class WebserviceUser implements UserInterface, EquatableInterface 8 { 9 private $username; 10 private $password; 11 private $salt; 12 private $roles; 13 14 public function __construct($username, $password, $salt, array $roles) 15 { 16 $this->username = $username; 17 $this->password = $password; 18 $this->salt = $salt; 19 $this->roles = $roles; 20 } 21 22 public function getRoles() 23 { 24 return $this->roles; 25 } 26 27 public function getPassword() 28 { 29 return $this->password; 30 } 31 32 public function getSalt() 33 { 34 return $this->salt; 35 } 36 37 public function getUsername() 38 { 39 return $this->username; 40 } 41 42 public function eraseCredentials() 43 { 44 } 45 46 public function isEqualTo(UserInterface $user) 47 { 48 if (!$user instanceof WebserviceUser) { 49 return false; 50 } 51 52 if ($this->password !== $user->getPassword()) { 53 return false; 54 } 55 56 if ($this->getSalt() !== $user->getSalt()) { 57 return false; 58 } 59 60 if ($this->username !== $user->getUsername()) { 61 return false; 62 } 63 64 return true;
65 66 }
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
class WebserviceUserProvider implements UserProviderInterface { public function loadUserByUsername($username) { // make a call to your webservice here $userData = ... // pretend it returns an array on success, false if there is no user if ($userData) { $password = '...';
// ...
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()); }
38 39 40 41 }
1 2 3 4 5 6 7
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 78-4
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 78-5
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 her password, the password is appended to the salt value and then encoded using this algorithm before being compared to the hashed password returned by your getPassword() method. Additionally, depending on your options, the password may be encoded multiple times and encoded to base64.
11. https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Security/Core/Encoder/MessageDigestPasswordEncoder.php
Chapter 79
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. There is plenty of great documentation on WSSE1, but this article will focus not on the security protocol, but rather the manner in which a custom protocol can be added to your Symfony2 application. The basis of WSSE is that a request header is checked for encrypted credentials, verified using a timestamp and nonce2, 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.
1. http://www.xml.com/pub/a/2003/12/17/dive.html 2. http://en.wikipedia.org/wiki/Cryptographic_nonce
The Token
The role of the token in the Symfony2 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 79-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
The WsseUserToken class extends the security component's AbstractToken3 class, which provides basic token functionality. Implement the TokenInterface4 on any class to use as a token.
The Listener
Next, you need a listener to listen on the security context. The listener is responsible for fielding requests to the firewall and calling the authentication provider. A listener must be an instance of ListenerInterface5. A security listener should handle the GetResponseEvent6 event, and set an authenticated token in the security context if successful.
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 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
class WsseListener implements ListenerInterface { protected $securityContext; protected $authenticationManager; public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager) { $this->securityContext = $securityContext; $this->authenticationManager = $authenticationManager; } public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/'; if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) { return; } $token = new WsseUserToken(); $token->setUser($matches[1]); $token->digest $token->nonce $token->created = $matches[2]; = $matches[3]; = $matches[4];
try { $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->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->securityContext->getToken(); // if ($token instanceof WsseUserToken && $this->providerKey === $token->getProviderKey()) { // $this->securityContext->setToken(null); // } // return; // Deny authentication with a '403 Forbidden' HTTP response $response = new Response(); $response->setStatusCode(403); $event->setResponse($response);
66 67
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 AuthenticationException7, a 403 Response is returned.
A class not used above, the AbstractAuthenticationListener8 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.
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
7. http://api.symfony.com/2.3/Symfony/Component/Security/Core/Exception/AuthenticationException.html 8. http://api.symfony.com/2.3/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.html
26 27 if ($user && $this->validateDigest($token->digest, $token->nonce, $token->created, 28 $user->getPassword())) { 29 $authenticatedToken = new WsseUserToken($user->getRoles()); 30 $authenticatedToken->setUser($user); 31 32 return $authenticatedToken; 33 } 34 35 throw new AuthenticationException('The WSSE authentication failed.'); 36 } 37 38 protected function validateDigest($digest, $nonce, $created, $secret) 39 { 40 // Check created time is not in the future 41 if (strtotime($created) > time()) { 42 return false; 43 } 44 45 // Expire timestamp after 5 minutes 46 if (time() - strtotime($created) > 300) { 47 return false; 48 } 49 50 // Validate nonce is unique within 5 minutes 51 if (file_exists($this->cacheDir.'/'.$nonce) && 52 file_get_contents($this->cacheDir.'/'.$nonce) + 300 > time()) { 53 throw new NonceExpiredException('Previously used nonce detected'); 54 } 55 // If cache directory does not exist we create it 56 if (!is_dir($this->cacheDir)) { 57 mkdir($this->cacheDir, 0777, true); 58 } 59 file_put_contents($this->cacheDir.'/'.$nonce, time()); 60 61 // Validate Secret 62 $expected = base64_encode(sha1(base64_decode($nonce).$created.$secret, true)); 63 64 return $digest === $expected; 65 } 66 67 public function supports(TokenInterface $token) 68 { return $token instanceof WsseUserToken; } }
The AuthenticationProviderInterface9 requires an authenticate method on the user token, and a supports method, which tells the authentication manager whether or not to use this provider for the given token. In the case of multiple providers, the authentication manager will then move to the next provider in the list.
9. http://api.symfony.com/2.3/Symfony/Component/Security/Core/Authentication/Provider/AuthenticationProviderInterface.html
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 your provider available to your security configuration? The answer is by using a 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 SecurityFactoryInterface10.
Listing 79-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
The SecurityFactoryInterface11 requires the following methods: create method, which adds the listener and authentication provider to the DI container for the appropriate security context;
10. http://api.symfony.com/2.3/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.html 11. http://api.symfony.com/2.3/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.html
getPosition method, which must be of type pre_auth, form, http, and remember_me and defines the position at which the provider is called; getKey method which defines the configuration key used to reference the provider; 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.
A class not used in this example, AbstractFactory12, 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 79-5
1 # src/Acme/DemoBundle/Resources/config/services.yml 2 services: 3 wsse.security.authentication.provider: 4 class: Acme\DemoBundle\Security\Authentication\Provider\WsseProvider 5 arguments: ["", "%kernel.cache_dir%/security/nonces"] 6 7 wsse.security.authentication.listener: 8 class: Acme\DemoBundle\Security\Firewall\WsseListener 9 arguments: ["@security.context", "@security.authentication.manager"]
Now that your services are defined, tell your security context about your factory in your bundle class:
Listing 79-6
1 2 3 4 5 6 7 8 9 10 11
12. http://api.symfony.com/2.3/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.html
12 13 14 15 16 17 }
You are finished! You can now define parts of your app as under WSSE protection.
Listing 79-7
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 79-8
1 class WsseFactory implements SecurityFactoryInterface 2 { 3 // ... 4 5 public function addConfiguration(NodeDefinition $node) 6 { 7 $node 8 ->children() 9 ->scalarNode('lifetime')->defaultValue(300) 10 ->end(); 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 79-9
1 class WsseFactory implements SecurityFactoryInterface 2 { 3 public function create(ContainerBuilder $container, $id, $config, $userProvider, 4 $defaultEntryPoint) 5 { 6 $providerId = 'security.authentication.provider.wsse.'.$id;
7 8 9 10 11 12 13 14 15 }
$container ->setDefinition($providerId, new DefinitionDecorator('wsse.security.authentication.provider')) ->replaceArgument(0, new Reference($userProvider)) ->replaceArgument(2, $config['lifetime']); // ... }
// ...
You'll also need to add a third argument to the wsse.security.authentication.provider service configuration, which can be blank, but will be filled in with the lifetime in the factory. The WsseProvider class will also now need to accept a third constructor argument - the lifetime - which it should use instead of the hard-coded 300 seconds. These two steps are not shown here.
The lifetime of each wsse request is now configurable, and can be set to any desirable value per firewall.
Listing 79-10
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 80
1 2 3 4 5 6 7 8 9 10
Chapter 80: How to change the Default Target Path Behavior | 292
11 12 13 14 15 16 17 18 19 }
// Do not save target path for XHR and non-GET requests // You can add any more logic here you want if ($request->isXmlHttpRequest() || 'GET' !== $request->getMethod()) { return; }
parent::setTargetPath($request); }
Chapter 80: How to change the Default Target Path Behavior | 293
Chapter 81
The serializer service is not available by default. To turn it on, activate it in your configuration:
Listing 81-1
You can load normalizers and/or encoders by tagging them as serializer.normalizer and serializer.encoder. It's also possible to set the priority of the tag in order to decide the matching order. Here an example on how to load the load the GetSetMethodNormalizer4:
Listing 81-2
The GetSetMethodNormalizer5 is broken by design. As soon as you have a circular object graph, an infinite loop is created when calling the getters. You're encouraged to add your own normalizers that fit your use-case.
4. http://api.symfony.com/2.3/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.html 5. http://api.symfony.com/2.3/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.html
Chapter 82
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
// Customize your response object to display the exception details $response = new Response(); $response->setContent($message); // HttpExceptionInterface is a special type of exception that // holds status code and header details if ($exception instanceof HttpExceptionInterface) {
1. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelEvents.html
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.
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 82-2
1 # app/config/config.yml 2 services: 3 kernel.listener.your_listener_name: 4 class: Acme\DemoBundle\EventListener\AcmeExceptionListener 5 tags: 6 - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
There is an additional tag option priority that is optional and defaults to 0. This value can be from -255 to 255, and the listeners will be executed in the order of their priority. This is useful when you need to guarantee that one listener is executed before another.
1 2 3 4 5 6 7 8 9 10 11 12
2. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/Event/GetResponseForExceptionEvent.html 3. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/KernelEvents.html
13 14 15 16 17 18 }
return; }
// ...
}
Two types of request are available in the HttpKernelInterface4 interface: HttpKernelInterface::MASTER_REQUEST and HttpKernelInterface::SUB_REQUEST.
4. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/HttpKernelInterface.html
Chapter 83
Understanding Scopes
The scope of a service controls how long an instance of a service is used by the container. The Dependency Injection component provides two generic scopes: container (the default one): The same instance is used each time you request it from this container. prototype: A new instance is created each time you request the service. The ContainerAwareHttpKernel1 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). 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 request service, you will receive a ScopeWideningInjectionException2 when compiling the container. Read the sidebar below for more details.
1. http://api.symfony.com/2.3/Symfony/Component/HttpKernel/DependencyInjection/ContainerAwareHttpKernel.html 2. http://api.symfony.com/2.3/Symfony/Component/DependencyInjection/Exception/ScopeWideningInjectionException.html
A service can of course depend on a service from a wider scope without any issue.
Injecting the container or setting your service to a narrower scope have drawbacks. For synchronized services (like the request), using setter injection is the best option as it has no drawbacks and everything works without any special code in your service or in your definition:
Listing 83-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Whenever the request scope is entered or left, the service container will automatically call the setRequest() method with the current request instance. You might have noticed that the setRequest() method accepts null as a valid value for the request argument. That's because when leaving the request scope, the request instance can be null (for the master request for instance). Of course, you should take care of this possibility in your code. This should also be taken into account when declaring your service:
Listing 83-2
You can declare your own synchronized services very easily; here is the declaration of the request service for reference:
Listing 83-3
The service using the synchronized service will need to be public in order to have its setter called when the scope changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Take care not to store the request 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 config for this class would look something like this:
Listing 83-6
1 # src/Acme/HelloBundle/Resources/config/services.yml 2 parameters: 3 # ... 4 my_mailer.class: Acme\HelloBundle\Mail\Mailer 5 services: 6 my_mailer: 7 class: "%my_mailer.class%" 8 arguments: ["@service_container"] 9 # 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).
If you define a controller as a service then you can get the Request object without injecting the container by having it passed in as an argument of your action method. See The Request as a Controller Argument for details.
Chapter 84
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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 85
1 2 3 4 5 6
use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionStorage; $proxy = new YourProxy(new PdoSessionStorage()); $session = new Session(new NativeSessionStorage($proxy));
Below, you'll learn two real examples that can be used for YourProxy: encryption of session data and readonly guest session.
1 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; 2 3 class EncryptedSessionProxy extends SessionHandlerProxy 4 { 5 private $key; 6 7 public function __construct(\SessionHandlerInterface $handler, $key) 8 { 9 $this->key = $key; 10 11 parent::__construct($handler); 12 } 13 14 public function read($id)
15 16 17 18 19 20 21 22 23 24 25 26 27 }
{ $data = parent::write($id, $data); 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
use Foo\User; use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; class ReadOnlyGuestSessionProxy 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 86
Creating 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 86-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Chapter 86: Making the Locale "Sticky" during a User's Session | 307
20 if (!$request->hasPreviousSession()) { 21 return; 22 } 23 24 // try to see if the locale has been set as a _locale routing parameter 25 if ($locale = $request->attributes->get('_locale')) { 26 $request->getSession()->set('_locale', $locale); 27 } else { 28 // if no explicit locale has been set on this request, use one from the session 29 $request->setLocale($request->getSession()->get('_locale', 30 $this->defaultLocale)); 31 } 32 } 33 34 public static function getSubscribedEvents() 35 { 36 return array( 37 // must be registered before the default Locale listener 38 KernelEvents::REQUEST => array(array('onKernelRequest', 17)), 39 ); 40 } }
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 86-3
1. http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html#getLocale()
Chapter 86: Making the Locale "Sticky" during a User's Session | 308
Chapter 87
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 87-1
Chapter 87: Configuring the Directory where Sessions Files are Saved | 309
Chapter 88
New in version 2.3: The ability to integrate with a legacy PHP session was added in Symfony 2.3.
If you're integrating the Symfony full-stack Framework into a legacy application that starts the session with session_start(), you may still be able to use Symfony's session management by using the PHP Bridge session. If the application has sets it's own PHP save handler, you can specify null for the handler_id:
Listing 88-1
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 88-2
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 89
Directory Structure
When looking at a Symfony2 project - for example, the Symfony2 Standard Edition1 - you'll notice a very different directory structure than in symfony1. The differences, however, are somewhat superficial.
In that way, the src directory is a bit like the plugins directory in symfony1, but much more flexible. Additionally, while your bundles will live in the src/ directory, third-party bundles will live somewhere in the vendor/ directory. To get a better picture of the src/ directory, let's first think of a symfony1 application. First, part of your code likely lives inside one or more applications. Most commonly these include modules, but could also include any other PHP classes you put in your application. You may have also created a schema.yml file in the config directory of your project and built several model files. Finally, to help with some common functionality, you're using several third-party plugins that live in the plugins/ directory. In other words, the code that drives your application lives in many different places. In Symfony2, life is much simpler because all Symfony2 code must live in a bundle. In the pretend symfony1 project, all the code could be moved into one or more plugins (which is a very good practice, in fact). Assuming that all modules, PHP classes, schema, routing configuration, etc were moved into a plugin, the symfony1 plugins/ directory would be very similar to the Symfony2 src/ directory. Put simply again, the src/ directory is where your code, assets, templates and most anything else specific to your project will live.
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 89-2
1 2 3 4 5 6 7 8 9
namespace Sensio\Bundle\FrameworkExtraBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; // ... class SensioFrameworkExtraBundle extends Bundle { // ... }
The file itself lives at vendor/sensio/framework-extra-bundle/Sensio/Bundle/ FrameworkExtraBundle/SensioFrameworkExtraBundle.php. As you can see, the second part 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/frameworkextra-bundle, spells out the directory that the file should live in (vendor/sensio/framework-extrabundle/Sensio/Bundle/FrameworkExtraBundle/). Composer can then look for the file at this specific place and load it very fast. If 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 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 Symfony2 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 89-3
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
2. http://getcomposer.org 3. http://getcomposer.org/doc/04-schema.md#autoload
1 $ php symfony
In Symfony2, the console is now in the app sub-directory and is called console:
Listing 89-5
1 $ php app/console
Applications
In a symfony1 project, it is common to have several applications: one for the frontend and one for the backend 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 frontend and the backend 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.
Read the definition of a Project, an Application, and a Bundle in the glossary.
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 12
// app/AppKernel.php public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), ..., new Acme\DemoBundle\AcmeDemoBundle(), );
return $bundles; }
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:
Listing 89-9
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 89-10
In Symfony2, you can also create arbitrary entries under the parameters key of your configuration:
Listing 89-11
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 90
Listing 90-4
Chapter 90: How to Inject Variables into all Templates (i.e. Global Variables) | 318
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 90-5
Chapter 90: How to Inject Variables into all Templates (i.e. Global Variables) | 319
Chapter 91
Usually, when you refer to a template, you'll use the MyBundle:Subdir:filename.html.twig format (see Template Naming and Locations). Twig also natively offers a feature called "namespaced paths", and support is built-in automatically for all of your bundles. Take the following paths as an example:
Listing 91-1
Chapter 91: How to use and Register namespaced Twig Paths | 320
The registered namespace is called foo_bar, which refers to the vendor/acme/foo-project/templates directory. Assuming there's a file called sidebar.twig in that directory, you can use it easily:
Listing 91-4
1 {% include '@foo_bar/side.bar.twig` %}
Chapter 91: How to use and Register namespaced Twig Paths | 321
Chapter 92
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 92-2
1 2 3 4 5 6 7
// src/Acme/HelloBundle/Controller/HelloController.php // ... public function indexAction($name) { return $this->render('AcmeHelloBundle:Hello:index.html.php', array('name' => $name)); }
shortcut
to
render
the
default
Chapter 92: How to use PHP instead of Twig for Templates | 322
5 6 7 8 9 10 11 12 13
// ... /** * @Template(engine="php") */ public function indexAction($name) { return array('name' => $name); }
Decorating Templates
More often than not, templates in a project share common elements, like the well-known header and footer. In Symfony2, 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 92-4
1 <!-- src/Acme/HelloBundle/Resources/views/Hello/index.html.php --> 2 <?php $view->extend('AcmeHelloBundle::layout.html.php') ?> 3 4 Hello <?php echo $name ?>!
The AcmeHelloBundle::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, let's have a look at the layout.html.php file:
Listing 92-5
1 2 3 4 5 6
The layout is itself decorated by another one (::base.html.php). Symfony2 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 store global views for your entire project:
Listing 92-6
1 2 3 4 5 6 7 8 9 10 11
<!-- app/Resources/views/base.html.php --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php $view['slots']->output('title', 'Hello Application') ?></title> </head> <body> <?php $view['slots']->output('_content') ?> </body> </html>
Chapter 92: How to use PHP instead of Twig for Templates | 323
For both layouts, the $view['slots']->output('_content') expression is replaced by the content of the child template, index.html.php and layout.html.php respectively (more on slots in the next section). As you can see, Symfony2 provides methods on a mysterious $view object. In a template, the $view variable is always available and refers to a special object that provides a bunch of methods that makes the template engine tick.
1 2 3 4 5 6
The base layout already has the code to output the title in the header:
Listing 92-8
1 <!-- app/Resources/views/base.html.php --> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 4 <title><?php $view['slots']->output('title', 'Hello Application') ?></title> 5 </head>
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 92-9
1 <?php $view['slots']->start('title') ?> 2 Some large amount of HTML 3 <?php $view['slots']->stop() ?>
1 <!-- src/Acme/HelloBundle/Resources/views/Hello/index.html.php --> 2 <?php $view->extend('AcmeHelloBundle::layout.html.php') ?> 3 4 <?php echo $view->render('AcmeHelloBundle:Hello:hello.html.php', array('name' => $name)) ?>
Chapter 92: How to use PHP instead of Twig for Templates | 324
The render() method evaluates and returns the content of another template (this is the exact same method as the one used in the controller).
1 <!-- src/Acme/HelloBundle/Resources/views/Hello/index.html.php --> 2 <?php echo $view['actions']->render( 3 new ControllerReference('AcmeHelloBundle:Hello:fancy', array( 4 'name' => $name, 5 'color' => 'green', 6 )) 7 ) ?>
Here, the AcmeHelloBundle:Hello:fancy string refers to the fancy action of the Hello controller:
Listing 92-13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// src/Acme/HelloBundle/Controller/HelloController.php
class HelloController extends Controller { public function fancyAction($name, $color) { // create some object, based on the $color variable $object = ...; return $this->render('AcmeHelloBundle: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 92: How to use PHP instead of Twig for Templates | 325
1 <a href="<?php echo $view['router']->generate('hello', array('name' => 'Thomas')) ?>"> 2 Greet Thomas! 3 </a>
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 92-15
1 # src/Acme/HelloBundle/Resources/config/routing.yml 2 hello: # The route name 3 path: /hello/{name} 4 defaults: { _controller: AcmeHelloBundle:Hello:index }
1 <link href="<?php echo $view['assets']->getUrl('css/blog.css') ?>" rel="stylesheet" 2 type="text/css" /> 3 <img src="<?php echo $view['assets']->getUrl('images/logo.png') ?>" />
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.
Output Escaping
When using PHP templates, escape variables whenever they are displayed to the user:
Listing 92-17
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:
Listing 92-18
Chapter 92: How to use PHP instead of Twig for Templates | 326
Chapter 93
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 93-1
1 2 3 4 5 6 7 8
1. https://github.com/fabpot/Twig-extensions 2. http://twig.sensiolabs.org/doc/advanced_legacy.html#creating-an-extension
9 new \Twig_SimpleFilter('price', array($this, 'priceFilter')), 10 ); 11 } 12 13 public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = 14 ',') 15 { 16 $price = number_format($number, $decimals, $decPoint, $thousandsSep); 17 $price = '$'.$price; 18 19 return $price; 20 } 21 22 public function getName() 23 { 24 return 'acme_extension'; 25 } }
Along with custom filters, you can also add custom functions and register global variables.
Keep in mind that Twig Extensions are not lazily loaded. This means that there's a higher chance that you'll get a CircularReferenceException or a ScopeWideningInjectionException if any services (or your Twig Extension in this case) are dependent on the request service. For more information take a look at How to work with Scopes.
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 94
The FrameworkBundle:Template:template controller will simply render whatever template you've passed as the template default value. You can of course also use this trick when rendering embedded controllers from within a template. But since the purpose of rendering a controller from within a template is typically to prepare some data in a custom controller, this is probably only useful if you'd like to cache this page partial (see Caching the static Template).
Listing 94-2
1 {{ render(url('acme_privacy')) }}
Since templates that are rendered in this way are typically static, it might make sense to cache them. Fortunately, this is easy! By configuring a few other variables in your route, you can control exactly how your page is cached:
Listing 94-3
1 acme_privacy: 2 path: /privacy 3 defaults: 4 _controller: FrameworkBundle:Template:template 5 template: 'AcmeBundle:Static:privacy.html.twig' 6 maxAge: 86400 7 sharedMaxAge: 86400
The maxAge and sharedMaxAge 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 sharedMaxAge are passed. If set to true, the Response will be marked as private.
Chapter 95
1 $client = static::createClient(array(), array( 2 'PHP_AUTH_USER' => 'username', 3 'PHP_AUTH_PW' => 'pa$$word', 4 ));
1 $client->request('DELETE', '/post/12', array(), array(), array( 2 'PHP_AUTH_USER' => 'username', 3 'PHP_AUTH_PW' => 'pa$$word', 4 ));
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 95-3
Chapter 96
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
Chapter 96: How to simulate Authentication with a Token in a Functional Test | 333
26 27 28 29 30 31 32 33 34 35 36 37 38 39 }
} private function logIn() { $session = $this->client->getContainer()->get('session'); $firewall = 'secured_area'; $token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN')); $session->set('_security_'.$firewall, serialize($token)); $session->save(); $cookie = new Cookie($session->getName(), $session->getId()); $this->client->getCookieJar()->set($cookie); }
The technique described in How to simulate HTTP Authentication in a Functional Test. is cleaner and therefore preferred way.
Chapter 96: How to simulate Authentication with a Token in a Functional Test | 334
Chapter 97
1 2 3 4 5 6 7 8
$harry = static::createClient(); $sally = static::createClient(); $harry->request('POST', '/say/sally/Hello'); $sally->request('GET', '/messages'); $this->assertEquals(201, $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 97-2
1 2 3 4 5 6 7 8 9 10 11
$harry = static::createClient(); $sally = static::createClient(); $harry->insulate(); $sally->insulate(); $harry->request('POST', '/say/sally/Hello'); $sally->request('GET', '/messages'); $this->assertEquals(201, $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 98
1 class HelloControllerTest extends WebTestCase 2 { 3 public function testIndex() 4 { 5 $client = static::createClient(); 6 7 // Enable the profiler for the next request (it does nothing if the profiler is 8 not available) 9 $client->enableProfiler(); 10 11 $crawler = $client->request('GET', '/hello/Fabien'); 12 13 // ... write some assertions about the Response 14 15 // Check that the profiler is enabled 16 if ($profile = $client->getProfile()) { 17 // check the number of requests 18 $this->assertLessThan( 19 10, 20 $profile->getCollector('db')->getQueryCount() 21 ); 22 23 // check the time spent in the framework 24 $this->assertLessThan( 25 500, 26 $profile->getCollector('time')->getDuration() 27 ); }
28 29 }
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:
Listing 98-2
1 $this->assertLessThan( 2 30, 3 $profile->get('db')->getQueryCount(), 4 sprintf( 5 'Checks that query count is less than 30 (token %s)', 6 $profile->getToken() 7 ) 8 );
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.
Chapter 99
Chapter 99: How to test code that interacts with the Database | 338
5 class SalaryCalculator 6 { 7 private $entityManager; 8 9 public function __construct(ObjectManager $entityManager) 10 { 11 $this->entityManager = $entityManager; 12 } 13 14 public function calculateTotalSalary($id) 15 { 16 $employeeRepository = 17 $this->entityManager->getRepository('AcmeDemoBundle::Employee'); 18 $employee = $userRepository->find($id); 19 20 return $employee->getSalary() + $employee->getBonus(); 21 } }
Since the ObjectManager gets injected into the class through the constructor, it's easy to pass a mock object within a test:
Listing 99-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
use Acme\DemoBundle\Salary\SalaryCalculator; class SalaryCalculatorTest extends \PHPUnit_Framework_TestCase { public function testCalculateTotalSalary() { // First, mock the object to be used in the test $employee = $this->getMock('\Acme\DemoBundle\Entity\Employee'); $employee->expects($this->once()) ->method('getSalary') ->will($this->returnValue(1000)); $employee->expects($this->once()) ->method('getBonus') ->will($this->returnValue(1100));
// Now, mock the repository so it returns the mock of the employee $employeeRepository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository') ->disableOriginalConstructor() ->getMock(); $employeeRepository->expects($this->once()) ->method('find') ->will($this->returnValue($employee)); // Last, mock the EntityManager to return the mock of the repository $entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager') ->disableOriginalConstructor() ->getMock(); $entityManager->expects($this->once()) ->method('getRepository') ->will($this->returnValue($employeeRepository));
$salaryCalculator = new SalaryCalculator($entityManager); $this->assertEquals(2100, $salaryCalculator->calculateTotalSalary(1));
Chapter 99: How to test code that interacts with the Database | 339
} }
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.
1 # app/config/config_test.yml 2 doctrine: 3 # ... 4 dbal: 5 host: localhost 6 dbname: testdb 7 user: testdb 8 password: testdb
Make sure that your database runs on localhost and has the defined database and user credentials set up.
Chapter 99: How to test code that interacts with the Database | 340
Chapter 100
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 WebTestCase, which makes all of this quite easy:
Listing 100-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/** * {@inheritDoc} */ public function setUp() { static::$kernel = static::createKernel(); static::$kernel->boot(); $this->em = static::$kernel->getContainer() ->get('doctrine') ->getManager() ;
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 }
Chapter 101
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';
file
bootstrap.php.cache
in
app/phpunit.xml.dist
with
<!-- app/phpunit.xml.dist --> <!-- ... --> <phpunit ... bootstrap = "tests.bootstrap.php" >
Now, you can define in your phpunit.xml.dist file which environment you want the cache to be cleared:
Listing 101-3
Chapter 101: How to customize the Bootstrap Process before running Tests | 343
This now becomes an environment variable (i.e. $_ENV) that's available in the custom bootstrap file (tests.bootstrap.php).
Chapter 101: How to customize the Bootstrap Process before running Tests | 344
Chapter 102
1 2 3 4 5 6 7 8 9 10 11 12
/** * @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.3/Symfony/Component/Validator/Constraint.html 2. http://api.symfony.com/2.3/Symfony/Component/Validator/Constraint.html
1 2 3 4 5
In other words, if you create a custom Constraint (e.g. MyConstraint), Symfony2 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 102-3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The validate method does not return a value; instead, it adds violations to the validator's context property with an addViolation method call if there are validation failures. Therefore, a value could be considered as being valid if it causes no violations to be added to the context. The first parameter of the addViolation call is the error message to use for that violation.
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.
Your constraint class should now use this alias to reference the appropriate validator:
Listing 102-6
As mentioned above, Symfony2 will automatically look for a class named after the constraint, with Validator appended. If your constraint validator is defined as a service, it's important that you override the validatedBy() method to return the alias used when defining your service, otherwise Symfony2 won't use the constraint validator service, and will instantiate the class instead, without any dependencies injected.
With this, the validator validate() method gets an object as its first argument:
Listing 102-8
1 class ProtocolClassValidator extends ConstraintValidator 2 { 3 public function validate($protocol, Constraint $constraint) 4 { 5 if ($protocol->getFoo() != $protocol->getBar()) { 6 $this->context->addViolationAt('foo', $constraint->message, array(), null); 7 } 8 } 9 }
Note that a class constraint validator is applied to the class itself, and not to the property:
Listing 102-9
Chapter 103
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 103-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Chapter 103: How to Create a SOAP Web Service in a Symfony2 Controller | 348
15 16 17 18 19 20 21 22 23 24 25 }
$message = \Swift_Message::newInstance() ->setTo('[email protected]') ->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 e-mail, 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 103-2
Below is an example of a controller that is capable of handling a SOAP request. If indexAction() is accessible via the route /soap, then the WSDL document can be retrieved via /soap?wsdl.
Listing 103-3
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.
4. http://php.net/manual/en/book.outcontrol.php
Chapter 103: How to Create a SOAP Web Service in a Symfony2 Controller | 349
Below is an example calling the service using NuSOAP5 client. This example assumes that the indexAction in the controller above is accessible via the route /soap:
Listing 103-4
1 <?xml version="1.0" encoding="ISO-8859-1"?> 2 <definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 3 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" 6 xmlns:tns="urn:arnleadservicewsdl" 7 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 8 xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 9 xmlns="http://schemas.xmlsoap.org/wsdl/" 10 targetNamespace="urn:helloservicewsdl"> 11 12 <types> 13 <xsd:schema targetNamespace="urn:hellowsdl"> 14 <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" /> 15 <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" /> 16 </xsd:schema> 17 </types> 18 19 <message name="helloRequest"> 20 <part name="name" type="xsd:string" /> 21 </message> 22 23 <message name="helloResponse"> 24 <part name="return" type="xsd:string" /> 25 </message> 26 27 <portType name="hellowsdlPortType"> 28 <operation name="hello"> 29 <documentation>Hello World</documentation> 30 <input message="tns:helloRequest"/> 31 <output message="tns:helloResponse"/> 32 </operation> 33 </portType> 34 35 <binding name="hellowsdlBinding" type="tns:hellowsdlPortType"> 36 <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> 37 <operation name="hello"> 38 <soap:operation soapAction="urn:arnleadservicewsdl#hello" style="rpc"/> 39 40 <input> 41 <soap:body use="encoded" namespace="urn:hellowsdl" 42 encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 43 </input> 44 45 <output> 46 <soap:body use="encoded" namespace="urn:hellowsdl" 47 encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 48 </output>
5. http://sourceforge.net/projects/nusoap
Chapter 103: How to Create a SOAP Web Service in a Symfony2 Controller | 350
49 </operation> 50 </binding> 51 52 <service name="hellowsdl"> 53 <port name="hellowsdlPort" binding="tns:hellowsdlBinding"> 54 <soap:address location="http://example.com/app.php/soap" /> 55 </port> 56 </service> 57 </definitions>
Chapter 103: How to Create a SOAP Web Service in a Symfony2 Controller | 351
Chapter 104
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 Creating Pages in Symfony2 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 Symfony2 project that's stored using the git1 source control management system.
1 2 3 4 5 6
1. http://git-scm.com/ 2. http://symfony.com/download
Chapter 104: How to Create and store a Symfony2 Project in git | 352
You may also want to create a .gitignore file that can be used system-wide, in which case, you can find more information here: Github .gitignore3 This way you can exclude files/folders often used by your IDE for all of your projects.
4. Copy app/config/parameters.yml to app/config/parameters.yml.dist. The parameters.yml file is ignored by git (see above) so that machine-specific settings like database passwords aren't committed. By creating the parameters.yml.dist file, new developers can quickly clone the project, copy this file to parameters.yml, customize it, and start developing. 5. Initialize your git repository:
Listing 104-2
1 $ git init
1 $ git add .
8. Finally, download all of the third-party vendor libraries by executing composer. For details, see Updating Vendors. At this point, you have a fully-functional Symfony2 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 Creating Pages in Symfony2 chapter to learn more about how to configure and develop inside your application.
The Symfony2 Standard Edition comes with some example functionality. To remove the sample code, follow the instructions in the "How to remove the AcmeDemoBundle" article.
Chapter 104: How to Create and store a Symfony2 Project in git | 353
If you want to add a new package to your application, modify the composer.json file:
Listing 104-5
and then execute the update command for this specific package, i.e.:
Listing 104-6
To learn more about Composer, see GetComposer.org5: It's important to realize that these vendor libraries are not actually part of your repository. Instead, they're simply un-tracked files that are downloaded into the vendor/. But since all the information needed to download these files is saved in composer.json and composer.lock (which are stored in the repository), any other developer can use the project, run php composer.phar install, and download the exact same set of vendor libraries. This means that you're controlling exactly what each vendor library looks like, without needing to actually commit them to your repository. So, whenever a developer uses your project, he/she should run the php composer.phar install script to ensure that all of the needed vendor libraries are downloaded.
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).
5. http://getcomposer.org/ 6. http://git-scm.com/book/en/Git-Tools-Submodules
Chapter 104: How to Create and store a Symfony2 Project in git | 354
The easiest way to store your project on a remote server is via GitHub7. Public repositories are free, however you will need to pay a monthly fee to host private repositories. Alternatively, you can store your git repository on any server by creating a barebones repository8 and then pushing to it. One library that helps manage this is Gitolite9.
Chapter 104: How to Create and store a Symfony2 Project in git | 355
Chapter 105
This entry is specifically about Subversion, and based on principles found in How to Create and store a Symfony2 Project in git.
Once you've read through Creating Pages in Symfony2 and become familiar with using Symfony, you'll no-doubt be ready to start your own project. The preferred method to manage Symfony2 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 Symfony2 project in a Subversion repository. There are several ways to do and this one is simply one that works.
Chapter 105: How to Create and store a Symfony2 Project in Subversion | 356
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).
1 $ mv Symfony/* myproject/
5. Let's 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 105-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/
$ svn propset svn:ignore "bundles" web $ svn ci -m "commit basic Symfony ignore list (vendor, app/bootstrap*, app/config/ parameters.yml, app/cache/*, app/logs/*, web/bundles)"
6. The rest of the files can now be added and committed to the project:
Listing 105-5
7. Copy app/config/parameters.yml to app/config/parameters.yml.dist. The parameters.yml file is ignored by svn (see above) so that machine-specific settings like database passwords aren't committed. By creating the parameters.yml.dist file, new developers can quickly clone the project, copy this file to parameters.yml, customize it, and start developing.
Chapter 105: How to Create and store a Symfony2 Project in Subversion | 357
8. Finally, download all of the third-party vendor libraries by executing composer. For details, see Updating Vendors.
If you rely on any "dev" versions, then git may be used to install those libraries, since there is no archive available for download.
At this point, you have a fully-functional Symfony2 project stored in your Subversion repository. The development can start with commits in the Subversion repository. You can continue to follow along with the Creating Pages in Symfony2 chapter to learn more about how to configure and develop inside your application.
The Symfony2 Standard Edition comes with some example functionality. To remove the sample code, follow the instructions in the "How to remove the AcmeDemoBundle" article.
and then execute the update command for this specific package, i.e.:
Listing 105-7
8. http://getcomposer.org/
Chapter 105: How to Create and store a Symfony2 Project in Subversion | 358
To learn more about Composer, see GetComposer.org9: It's important to realize that these vendor libraries are not actually part of your repository. Instead, they're simply un-tracked files that are downloaded into the vendor/. But since all the information needed to download these files is saved in composer.json and composer.lock (which are stored in the repository), any other developer can use the project, run php composer.phar install, and download the exact same set of vendor libraries. This means that you're controlling exactly what each vendor library looks like, without needing to actually commit them to your repository. So, whenever a developer uses your project, he/she should run the php composer.phar install script to ensure that all of the needed vendor libraries are downloaded.
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).
9. http://getcomposer.org/ 10. http://git-scm.com/ 11. http://subversion.apache.org/ 12. https://github.com/ 13. http://code.google.com/hosting/ 14. http://sourceforge.net/ 15. http://gna.org/
Chapter 105: How to Create and store a Symfony2 Project in Subversion | 359