Symfony Best Practices 2.7
Symfony Best Practices 2.7
Version: 2.7
generated on April 13, 2016
The Best Practices Book (2.7)
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
The Symfony Framework is well-known for being really flexible and is used to build micro-sites,
enterprise applications that handle billions of connections and even as the basis for other frameworks.
Since its release in July 2011, the community has learned a lot about what's possible and how to do things
best.
These community resources - like blog posts or presentations - have created an unofficial set of
recommendations for developing Symfony applications. Unfortunately, a lot of these recommendations
are unneeded for web applications. Much of the time, they unnecessarily overcomplicate things and don't
follow the original pragmatic philosophy of Symfony.
Best practice is a noun that means "a well defined procedure that is known to produce near-
optimum results". And that's exactly what this guide aims to provide. Even if you don't agree
with every recommendation, we believe these will help you build great applications with less
complexity.
• Websites and web applications developed with the full-stack Symfony Framework.
For other situations, this guide might be a good starting point that you can then extend and fit to your
specific needs:
1. https://connect.sensiolabs.com/profile/fabpot
We know that old habits die hard and some of you will be shocked by some of these best practices. But
by following these, you'll be able to develop apps faster, with less complexity and with the same or even
higher quality. It's also a moving target that will continue to improve.
Keep in mind that these are optional recommendations that you and your team may or may not
follow to develop Symfony applications. If you want to continue using your own best practices and
methodologies, you can of course do it. Symfony is flexible enough to adapt to your needs. That will
never change.
The Application
In addition to this guide, a sample application has been developed with all these best practices in mind.
This project, called the Symfony Demo application, can be obtained through the Symfony Installer. First,
download and install2 the installer and then execute this command to download the demo application:
The demo application is a simple blog engine, because that will allow us to focus on the Symfony
concepts and features without getting buried in difficult implementation details. Instead of developing
the application step by step in this guide, you'll find selected snippets of code through the chapters.
• Your existing applications are not wrong, they just follow another set of guidelines;
• A full codebase refactorization is prone to introduce errors in your applications;
• The amount of work spent on this could be better dedicated to improving your tests or adding
features that provide real value to the end users.
2. https://symfony.com/download
Installing Symfony
In the past, Symfony projects were created with Composer1, the dependency manager for PHP
applications. However, the current recommendation is to use the Symfony Installer, which has to be
installed before creating your first project.
Read the installation chapter of the Symfony Book to learn how to install and use the Symfony Installer.
If the installer doesn't work for you or doesn't output anything, make sure that the Phar extension2
is installed and enabled on your computer.
1. https://getcomposer.org/
2. http://php.net/manual/en/intro.phar.php
Symfony releases are digitally signed for security reasons. If you want to verify the integrity of your
Symfony installation, take a look at the public checksums repository3 and follow these steps4 to verify
the signatures.
This file and directory hierarchy is the convention proposed by Symfony to structure your applications.
The recommended purpose of each directory is the following:
Application Bundles
When Symfony 2.0 was released, most developers naturally adopted the symfony 1.x way of dividing
applications into logical modules. That's why many Symfony apps use bundles to divide their code into
logical features: UserBundle, ProductBundle, InvoiceBundle, etc.
But a bundle is meant to be something that can be reused as a stand-alone piece of software. If
UserBundle cannot be used "as is" in other Symfony apps, then it shouldn't be its own bundle. Moreover,
if InvoiceBundle depends on ProductBundle, then there's no advantage to having two separate bundles.
Create only one bundle called AppBundle for your application logic.
3. https://github.com/sensiolabs/checksums
4. http://fabien.potencier.org/signing-project-releases.html
There is no need to prefix the AppBundle with your own vendor (e.g. AcmeAppBundle), because
this application bundle is never going to be shared.
Another reason to create a new bundle is when you're overriding something in a vendor's bundle
(e.g. a controller). See How to Use Bundle Inheritance to Override Parts of a Bundle.
All in all, this is the typical directory structure of a Symfony application that follows these best practices:
If your Symfony installation doesn't come with a pre-generated AppBundle, you can generate it by
hand executing this command:
The changes are pretty superficial, but for now, we recommend that you use the Symfony directory
structure.
Configuration usually involves different application parts (such as infrastructure and security credentials)
and different environments (development, production). That's why Symfony recommends that you split
the application configuration into three parts.
Infrastructure-Related Configuration
Define the infrastructure-related configuration options in the app/config/parameters.yml file.
The default parameters.yml file follows this recommendation and defines the options related to the
database and mail server infrastructure:
These options aren't defined inside the app/config/config.yml file because they have nothing to do
with the application's behavior. In other words, your application doesn't care about the location of your
database or the credentials to access to it, as long as the database is correctly configured.
Canonical Parameters
Since version 2.3, Symfony includes a configuration file called parameters.yml.dist, which stores the
canonical list of configuration parameters for the application.
Whenever a new configuration parameter is defined for the application, you should also add it to this
file and submit the changes to your version control system. Then, whenever a developer updates the
project or deploys it to a server, Symfony will check if there is any difference between the canonical
parameters.yml.dist file and your local parameters.yml file. If there is a difference, Symfony will ask
you to provide a value for the new parameter and it will add it to your local parameters.yml file.
Application-Related Configuration
Define the application behavior related configuration options in the app/config/config.yml file.
The config.yml file contains the options used by the application to modify its behavior, such as the
sender of email notifications, or the enabled feature toggles1. Defining these values in parameters.yml
file would add an extra layer of configuration that's not needed because you don't need or want these
configuration values to change on each server.
The configuration options defined in the config.yml file usually vary from one environment to another.
That's why Symfony already includes app/config/config_dev.yml and app/config/config_prod.yml
files so that you can override specific values for each environment.
The traditional approach for defining configuration options has caused many Symfony apps to include
an option like the following, which would be used to control the number of posts to display on the blog
homepage:
If you've done something like this in the past, it's likely that you've in fact never actually needed to change
that value. Creating a configuration option for a value that you are never going to configure just isn't
necessary. Our recommendation is to define these values as constants in your application. You could, for
example, define a NUM_ITEMS constant in the Post entity:
1. https://en.wikipedia.org/wiki/Feature_toggle
The main advantage of defining constants is that you can use their values everywhere in your application.
When using parameters, they are only available from places with access to the Symfony container.
Constants can be used for example in your Twig templates thanks to the constant() function2:
And Doctrine entities and repositories can now easily access these values, whereas they cannot access the
container parameters:
The only notable disadvantage of using constants for this kind of configuration values is that you cannot
redefine them easily in your tests.
As explained in How to Load Service Configuration inside a Bundle article, Symfony bundles have two
choices on how to handle configuration: normal service configuration through the services.yml file and
semantic configuration through a special *Extension class.
Although semantic configuration is much more powerful and provides nice features such as configuration
validation, the amount of work needed to define that configuration isn't worth it for bundles that aren't
meant to be shared as third-party bundles.
2. http://twig.sensiolabs.org/doc/functions/constant.html
In computer software, business logic or domain logic is "the part of the program that encodes the real-
world business rules that determine how data can be created, displayed, stored, and changed" (read full
definition1).
In Symfony applications, business logic is all the custom code you write for your app that's not specific to
the framework (e.g. routing and controllers). Domain classes, Doctrine entities and regular PHP classes
that are used as services are good examples of business logic.
For most projects, you should store everything inside the AppBundle. Inside here, you can create
whatever directories you want to organize things:
1. https://en.wikipedia.org/wiki/Business_logic
The recommended approach of using the AppBundle/ directory is for simplicity. If you're advanced
enough to know what needs to live in a bundle and what can live outside of one, then feel free to
do that.
Traditionally, the naming convention for a service involved following the class name and location to
avoid name collisions. Thus, the service would have been called app.utils.slugger. But by using short
service names, your code will be easier to read and use.
The name of your application's services should be as short as possible, but unique enough that you can search
your project for the service if you ever need to.
Now you can use the custom slugger in any controller class, such as the AdminController:
This is controversial, and in our experience, YAML and XML usage is evenly distributed among
developers, with a slight preference towards YAML. Both formats have the same performance, so this is
ultimately a matter of personal taste.
We recommend YAML because it's friendly to newcomers and concise. You can of course use whatever
format you like.
This practice is cumbersome and completely unnecessary for your own services:
This practice was wrongly adopted from third-party bundles. When Symfony introduced its service
container, some developers used this technique to easily allow overriding services. However, overriding
a service by just changing its class name is a very rare use case because, frequently, the new service has
different constructor arguments.
If you're more advanced, you can of course store them under your own namespace in src/.
Annotations are by far the most convenient and agile way of setting up and looking for mapping
information:
2. http://www.doctrine-project.org/
All formats have the same performance, so this is once again ultimately a matter of taste.
Data Fixtures
As fixtures support is not enabled by default in Symfony, you should execute the following command to
install the Doctrine fixtures bundle:
Then, enable the bundle in AppKernel.php, but only for the dev and test environments:
We recommend creating just one fixture class3 for simplicity, though you're welcome to have more if that
class gets quite large.
Assuming you have at least one fixtures class and that the database access is configured properly, you can
load your fixtures by executing the following command:
Coding Standards
The Symfony source code follows the PSR-14 and PSR-25 coding standards that were defined by the PHP
community. You can learn more about the Symfony Coding standards and even use the PHP-CS-Fixer6,
which is a command-line utility that can fix the coding standards of an entire codebase in a matter of
seconds.
3. https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html#writing-simple-fixtures
4. http://www.php-fig.org/psr/psr-1/
5. http://www.php-fig.org/psr/psr-2/
6. https://github.com/FriendsOfPHP/PHP-CS-Fixer
Symfony follows the philosophy of "thin controllers and fat models". This means that controllers should
hold just the thin layer of glue-code needed to coordinate the different parts of the application.
As a rule of thumb, you should follow the 5-10-20 rule, where controllers should only define 5 variables
or less, contain 10 actions or less and include 20 lines of code or less in each action. This isn't an exact
science, but it should help you realize when code should be refactored out of the controller and into a
service.
Make your controller extend the FrameworkBundle base controller and use annotations to configure routing,
caching and security whenever possible.
Coupling the controllers to the underlying framework allows you to leverage all of its features and
increases your productivity.
And since your controllers should be thin and contain nothing more than a few lines of glue-code,
spending hours trying to decouple them from your framework doesn't benefit you in the long run. The
amount of time wasted isn't worth the benefit.
In addition, using annotations for routing, caching and security simplifies configuration. You don't need
to browse tens of files created with different formats (YAML, XML, PHP): all the configuration is just
where you need it and it only uses one format.
Overall, this means you should aggressively decouple your business logic from the framework while, at
the same time, aggressively coupling your controllers and routing to the framework in order to get the
most out of it.
Routing Configuration
To load routes defined as annotations in your controllers, add the following configuration to the main
routing configuration file:
Template Configuration
Don't use the @Template annotation to configure the template used by the controller.
The @Template annotation is useful, but also involves some magic. We don't think its benefit is worth
the magic, and so recommend against using it.
Most of the time, @Template is used without any parameters, which makes it more difficult to know
which template is being rendered. It also makes it less obvious to beginners that a controller should
always return a Response object (unless you're using a view layer).
Use the ParamConverter trick to automatically query for Doctrine entities when it's simple and convenient.
For example:
Normally, you'd expect a $id argument to showAction(). Instead, by creating a new argument ($post)
and type-hinting it with the Post class (which is a Doctrine entity), the ParamConverter automatically
queries for an object whose $id property matches the {id} value. It will also show a 404 page if no Post
can be found.
1. https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
You can also use the @ParamConverter configuration, which is infinitely flexible:
The point is this: the ParamConverter shortcut is great for simple situations. But you shouldn't forget that
querying for entities directly is still very easy.
When PHP was created 20 years ago, developers loved its simplicity and how well it blended HTML
and dynamic code. But as time passed, other template languages - like Twig1 - were created to make
templating even better.
Generally speaking, PHP templates are much more verbose than Twig templates because they lack native
support for lots of modern features needed by templates, like inheritance, automatic escaping and named
arguments for filters and functions.
Twig is the default templating format in Symfony and has the largest community support of all non-PHP
template engines (it's used in high profile projects such as Drupal 8).
In addition, Twig is the only template format with guaranteed support in Symfony 3.0. As a matter of
fact, PHP may be removed from the officially supported template engines.
Template Locations
Store all your application's templates in app/Resources/views/ directory.
Traditionally, Symfony developers stored the application templates in the Resources/views/ directory
of each bundle. Then they used the logical name to refer to them (e.g.
AcmeDemoBundle:Default:index.html.twig).
But for the templates used in your application, it's much more convenient to store them in the app/
Resources/views/ directory. For starters, this drastically simplifies their logical names:
1. http://twig.sensiolabs.org/
Another advantage is that centralizing your templates simplifies the work of your designers. They don't
need to look for templates in lots of directories scattered through lots of bundles.
Twig Extensions
Define your Twig extensions in the AppBundle/Twig/ directory and configure them using the app/config/
services.yml file.
Our application needs a custom md2html Twig filter so that we can transform the Markdown contents of
each post into HTML.
To do this, first, install the excellent Parsedown2 Markdown parser as a new dependency of the project:
Then, create a new Markdown service that will be used later by the Twig extension. The service definition
only requires the path to the class:
And the Markdown class just needs to define one single method to transform Markdown content into
HTML:
2. http://parsedown.org/
Next, create a new Twig extension and define a new filter called md2html using the Twig_SimpleFilter
class. Inject the newly defined markdown service in the constructor of the Twig extension:
Lastly define a new service to enable this Twig extension in the app (the service name is irrelevant because
you never use it in your own code):
Forms are one of the most misused Symfony components due to its vast scope and endless list of features.
In this chapter we'll show you some of the best practices so you can leverage forms but get work done
quickly.
Building Forms
Define your forms as PHP classes.
The Form component allows you to build forms right inside your controller code. This is perfectly fine
if you don't need to reuse the form somewhere else. But for organization and reuse, we recommend that
you define each form in its own PHP class:
Put the form type classes in the AppBundle\Form namespace, unless you use other custom form classes like
data transformers.
To use the class, use createForm() and instantiate the new class:
Add buttons in the templates, not in the form classes or the controllers.
Since Symfony 2.3, you can add buttons as fields on your form. This is a nice way to simplify the template
that renders your form. But if you add the buttons directly in your form class, this would effectively limit
the scope of that form:
This form may have been designed for creating posts, but if you wanted to reuse it for editing posts, the
button label would be wrong. Instead, some developers configure form buttons in the controller:
This is also an important error, because you are mixing presentation markup (labels, CSS classes, etc.)
with pure PHP code. Separation of concerns is always a good practice to follow, so put all the view-related
things in the view layer:
Listing 7-6
If you need more control over how your fields are rendered, then you should remove the
form_widget(form) function and render your fields individually. See the How to Customize Form
Rendering cookbook article for more information on this and how you can control how the form renders
at a global level using form theming.
There are really only two notable things here. First, we recommend that you use a single action for both
rendering the form and handling the form submit. For example, you could have a newAction() that only
renders the form and a createAction() that only processes the form submit. Both those actions will be
almost identical. So it's much simpler to let newAction() handle everything.
Second, we recommend using $form->isSubmitted() in the if statement for clarity. This isn't
technically needed, since isValid() first calls isSubmitted(). But without this, the flow doesn't read
well as it looks like the form is always processed (even on the GET request).
Custom form field types inherit from the AbstractType class, which defines the getName() method to
configure the name of that form type. These names must be unique in the application.
If a custom form type uses the same name as any of the Symfony's built-in form types, it will override
it. The same happens when the custom form type matches any of the types defined by the third-party
bundles installed in your application.
Internationalization and localization adapt the applications and their contents to the specific region or
language of the users. In Symfony this is an opt-in feature that needs to be enabled before using it. To do
this, uncomment the following translator configuration option and set your application locale:
Of all the available translation formats, only XLIFF and gettext have broad support in the tools used by
professional translators. And since it's based on XML, you can validate XLIFF file contents as you write
them.
Symfony 2.6 added support for notes inside XLIFF files, making them more user-friendly for translators.
At the end, good translations are all about context, and these XLIFF notes allow you to define that
context.
The Apache-licensed JMSTranslationBundle1 offers you a web interface for viewing and editing
these translation files. It also has advanced extractors that can read your project and automatically
update the XLIFF files.
Traditionally, Symfony developers have created these files in the Resources/translations/ directory
of each bundle. But since the app/Resources/ directory is considered the global location for the
application's resources, storing translations in app/Resources/translations/ centralizes them and
gives them priority over any other translation file. This let's you override translations defined in third-
party bundles.
Translation Keys
Always use keys for translations instead of content strings.
Using keys simplifies the management of the translation files because you can change the original
contents without having to update all of the translation files.
Keys should always describe their purpose and not their location. For example, if a form has a field with
the label "Username", then a nice key would be label.username, not edit_form.label.username.
1. https://github.com/schmittjoh/JMSTranslationBundle
Unless you have two legitimately different authentication systems and users (e.g. form login for the main site
and a token system for your API only), we recommend having only one firewall entry with the anonymous key
enabled.
Most applications only have one authentication system and one set of users. For this reason, you only
need one firewall entry. There are exceptions of course, especially if you have separated web and API
sections on your site. But the point is to keep things simple.
Additionally, you should use the anonymous key under your firewall. If you need to require users to be
logged in for different sections of your site (or maybe nearly all sections), use the access_control area.
If your users have a password, then we recommend encoding it using the bcrypt encoder, instead of the
traditional SHA-512 hashing encoder. The main advantages of bcrypt are the inclusion of a salt value to
protect against rainbow table attacks, and its adaptive nature, which allows to make it slower to remain
resistant to brute-force search attacks.
With this in mind, here is the authentication setup from our application, which uses a login form to load
users from the database:
The source code for our project contains comments that explain each part.
There are also different ways to centralize your authorization logic, like with a custom security voter or
with ACL.
Listing 9-2
Notice that this requires the use of the ParamConverter2, which automatically queries for the Post object
and puts it on the $post argument. This is what makes it possible to use the post variable in the
expression.
This has one major drawback: an expression in an annotation cannot easily be reused in other parts of
the application. Imagine that you want to add a link in a template that will only be seen by authors. Right
now you'll need to repeat the expression code using Twig syntax:
The easiest solution - if your logic is simple enough - is to add a new method to the Post entity that
checks if a given user is its author:
1. http://symfony.com/doc/current/components/expression_language/introduction.html
2. http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
Now you can reuse this method both in the template and in the security expression:
Security Voters
If your security logic is complex and can't be centralized into a method like isAuthor(), you should
leverage custom voters. These are an order of magnitude easier than ACLs and will give you the flexibility
you need in almost all cases.
First, create a voter class. The following example shows a voter that implements the same
getAuthorEmail logic you used above:
Now, you can use the voter with the @Security annotation:
You can also use this directly with the security.authorization_checker service or via the even easier
shortcut in a controller:
3. https://github.com/FriendsOfSymfony/FOSUserBundle
Web assets are things like CSS, JavaScript and image files that make the frontend of your site look
and work great. Symfony developers have traditionally stored these assets in the Resources/public/
directory of each bundle.
Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your
designers' lives will be much easier if all the application assets are in one location.
Templates also benefit from centralizing your assets, because the links are much more concise:
Keep in mind that web/ is a public directory and that anything stored here will be publicly
accessible, including all the original asset files (e.g. Sass, LESS and CoffeeScript files).
Using Assetic
These days, you probably can't simply create static CSS and JavaScript files and include them in your
template. Instead, you'll probably want to combine and minify these to improve client-side performance.
You may also want to use LESS or Sass (for example), which means you'll need some way to process these
into CSS files.
A lot of tools exist to solve these problems, including pure-frontend (non-PHP) tools like GruntJS.
Assetic is an asset manager capable of compiling assets developed with a lot of different frontend
technologies like LESS, Sass and CoffeeScript. Combining all your assets with Assetic is a matter of
wrapping all the assets with a single Twig tag:
Frontend-Based Applications
Recently, frontend technologies like AngularJS have become pretty popular for developing frontend web
applications that talk to an API.
If you are developing an application like this, you should use the tools that are recommended by the
technology, such as Bower and GruntJS. You should develop your frontend application separately from
your Symfony backend (even separating the repositories if you want).
1. https://github.com/kriswallsmith/assetic
Roughly speaking, there are two types of test. Unit testing allows you to test the input and output of
specific functions. Functional testing allows you to command a "browser" where you browse to pages on
your site, click links, fill out forms and assert that you see certain things on the page.
Unit Tests
Unit tests are used to test your "business logic", which should live in classes that are independent of
Symfony. For that reason, Symfony doesn't really have an opinion on what tools you use for unit testing.
However, the most popular tools are PhpUnit1 and PhpSpec2.
Functional Tests
Creating really good functional tests can be tough so some developers skip these completely. Don't skip
the functional tests! By defining some simple functional tests, you can quickly spot any big errors before
you deploy them:
Define a functional test that at least checks if your application pages are successfully loading.
1. https://phpunit.de/
2. http://www.phpspec.net/
This code checks that all the given URLs load successfully, which means that their HTTP response status
code is between 200 and 299. This may not look that useful, but given how little effort this took, it's
worth having it in your application.
In computer software, this kind of test is called smoke testing3 and consists of "preliminary testing to reveal
simple failures severe enough to reject a prospective software release".
Hardcode the URLs used in the functional tests instead of using the URL generator.
Consider the following functional test that uses the router service to generate the URL of the tested page:
This will work, but it has one huge drawback. If a developer mistakenly changes the path of the
blog_archives route, the test will still pass, but the original (old) URL won't work! This means that any
bookmarks for that URL will be broken and you'll lose any search engine page ranking.
3. https://en.wikipedia.org/wiki/Smoke_testing_(software)
4. http://mink.behat.org
5. https://github.com/hautelook/AliceBundle
6. https://github.com/fzaninotto/Faker
7. https://github.com/nelmio/alice