Symfony Quick Tour 3.4
Symfony Quick Tour 3.4
Version: 3.4
generated on July 17, 2017
What could be better to make up your own mind than to try out Symfony yourself? Aside from
a little time, it will cost you nothing. Step by step you will explore the Symfony universe. Be
careful, Symfony can become addictive from the very first encounter!
The Quick Tour (3.4)
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
Start using Symfony in 10 minutes! This chapter will walk you through the most important concepts
behind Symfony and explain how you can get started quickly by showing you a simple project in action.
If you've used a web framework before, you should feel right at home with Symfony. If not, welcome to
a whole new way of developing web applications.
Installing Symfony
Before continuing reading this chapter, make sure to have installed both PHP and Symfony as explained
in the Installing & Setting up the Symfony Framework article.
In Symfony applications, controllers are usually PHP classes whose names are suffixed with the
Controller word. In this example, the controller is called Default and the PHP class is called
DefaultController.
The methods defined in a controller are called actions, they are usually associated with one URL of the
application and their names are suffixed with Action. In this example, the Default controller has only
one action called index and defined in the indexAction() method.
Actions are usually very short - around 10-15 lines of code - because they just call other parts of the
application to get or generate the needed information and then they render a template to show the results
to the user.
In this example, the index action is practically empty because it doesn't need to call any other method.
The action just renders a template to welcome you to Symfony.
Routing
Symfony routes each request to the action that handles it by matching the requested URL against
the paths configured by the application. Open again the src/AppBundle/Controller/
DefaultController.php file and take a look at the three lines of code above the indexAction()
method:
In addition to PHP annotations, routes can be configured in YAML, XML or PHP files, as explained
in the Routing guide. This flexibility is one of the main features of Symfony, a framework that never
imposes a particular configuration format on you.
Templates
The only content of the index action is this PHP instruction:
Listing 1-3
return $this->render('default/index.html.twig', [
// ...
]);
The $this->render() method is a convenient shortcut to render a template. Symfony provides some
useful shortcuts to any controller extending from the base Symfony Controller1 class.
By default, application templates are stored in the app/Resources/views/ directory. Therefore,
the default/index.html.twig template corresponds to the app/Resources/views/default/
index.html.twig. Open that file and you'll see the following code:
Listing 1-4 1 {# app/Resources/views/default/index.html.twig #}
2 {% extends 'base.html.twig' %}
3
4 {% block body %}
5 <h1>Welcome to Symfony</h1>
6
7 {# ... #}
8 {% endblock %}
This template is created with Twig2, a template engine created for modern PHP applications. The second
part of this tutorial explains how templates work in Symfony.
1. http://api.symfony.com/3.4/Symfony/Bundle/FrameworkBundle/Controller/Controller.html
2. http://twig.sensiolabs.org/
This tool provides so much internal information about your application that you may be worried about
your visitors accessing sensible information. Symfony is aware of this issue and for that reason, it won't
display this bar when your application is running in the production server.
How does Symfony know whether your application is running locally or on a production server? Keep
reading to discover the concept of execution environments.
What is an Environment?
An environment represents a group of configurations that's used to run your application. Symfony
defines two environments by default: dev (suited for when developing the application locally) and prod
(optimized for when executing the application on production).
When you visit the http://localhost:8000 URL in your browser, you're executing your Symfony
application in the dev environment. To visit your application in the prod environment, visit the
http://localhost:8000/app.php URL instead. If you prefer to always show the dev environment
in the URL, you can visit http://localhost:8000/app_dev.php URL.
In this example, the config_dev.yml configuration file imports the common config.yml file and
then overrides any existing web debug toolbar configuration with its own options.
For more details on environments, see the "Environments" section of the Configuration guide.
Final Thoughts
Congratulations! You've had your first taste of Symfony code. That wasn't so hard, was it? There's a lot
more to explore, but you should already see how Symfony makes it really easy to implement web sites
better and faster. If you are eager to learn more about Symfony, dive into the next section: "The View".
After reading the first part of this tutorial, you have decided that Symfony was worth another 10 minutes.
In this second part, you will learn more about Twig1, the fast, flexible and secure template engine for PHP
applications. Twig makes your templates more readable and concise; it also makes them more friendly
for web designers.
{% ... %}
Controls the logic of the template; it is used for example to execute for loops and if statements.
{# ... #}
Allows including comments inside templates. Contrary to HTML comments, they aren't included
in the rendered template.
Below is a minimal template that illustrates a few basics, using two variables page_title and
navigation, which would be passed into the template:
Listing 2-1 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>{{ page_title }}</title>
5 </head>
1. http://twig.sensiolabs.org/
2. http://twig.sensiolabs.org/documentation
To render a template in Symfony, use the render() method from within a controller. If the template
needs variables to generate its contents, pass them as an array using the second optional argument:
Listing 2-2
$this->render('default/index.html.twig', array(
'variable_name' => 'variable_value',
));
Variables passed to a template can be strings, arrays or even objects. Twig abstracts the difference
between them and lets you access "attributes" of a variable with the dot (.) notation. The following code
listing shows how to display the content of a variable passed by the controller depending on its type:
Decorating Templates
More often than not, templates in a project share common elements, like the well-known header and
footer. Twig solves this problem elegantly with a concept called "template inheritance". This feature
allows you to build a base template that contains all the common elements of your site and defines
"blocks" of contents that child templates can override.
The index.html.twig template uses the extends tag to indicate that it inherits from the
base.html.twig template:
Listing 2-4 1 {# app/Resources/views/default/index.html.twig #}
2 {% extends 'base.html.twig' %}
3
4 {% block body %}
The {% block %} tags tell the template engine that a child template may override those portions of
the template. In this example, the index.html.twig template overrides the body block, but not the
title block, which will display the default content defined in the base.html.twig template.
Don't forget to check out the official Twig documentation3 to learn everything about filters, functions and
tags.
3. http://twig.sensiolabs.org/documentation
The path() function takes the route name as the first argument and you can optionally pass an array of
route parameters as the second argument.
The asset() function looks for the web assets inside the web/ directory. If you store them in another
directory, read this article to learn how to manage web assets.
Using the asset() function, your application is more portable. The reason is that you can move the
application root directory anywhere under your web root directory without changing anything in your
template's code.
Final Thoughts
Twig is simple yet powerful. Thanks to layouts, blocks, templates and action inclusions, it is very easy to
organize your templates in a logical and extensible way.
You have only been working with Symfony for about 20 minutes, but you can already do pretty amazing
stuff with it. That's the power of Symfony. Learning the basics is easy and you will soon learn that this
simplicity is hidden under a very flexible architecture.
But I'm getting ahead of myself. First, you need to learn more about the controller and that's exactly the
topic of the next part of this tutorial. Ready for another 10 minutes with Symfony?
Still here after the first two parts? You are already becoming a Symfony fan! Without further ado, discover
what controllers can do for you.
Open your browser and access the http://localhost:8000/hello/fabien URL to see the result
of executing this new action. Instead of the action result, you'll see an error page. As you probably
guessed, the cause of this error is that we're trying to render a template (default/hello.html.twig)
that doesn't exist yet.
Create the new app/Resources/views/default/hello.html.twig template with the following
content:
Browse again the http://localhost:8000/hello/fabien URL and you'll see this new template
rendered with the information passed by the controller. If you change the last part of the URL (e.g.
http://localhost:8000/hello/thomas) and reload your browser, the page will display a
different message. And if you remove the last part of the URL (e.g. http://localhost:8000/
hello), Symfony will display an error because the route expects a name and you haven't provided it.
Using Formats
Nowadays, a web application should be able to deliver more than just HTML pages. From XML for RSS
feeds or Web Services, to JSON for Ajax requests, there are plenty of different formats to choose from.
Obviously, when you support several request formats, you have to provide a template for each of the
supported formats. In this case, you should create a new hello.xml.twig template:
Now, when you browse to http://localhost:8000/hello/fabien, you'll see the regular HTML
page because html is the default format. When visiting http://localhost:8000/hello/
fabien.html you'll get again the HTML page, this time because you explicitly asked for the html
format. Lastly, if you visit http://localhost:8000/hello/fabien.xml you'll see the new XML
template rendered in your browser.
That's all there is to it. For standard formats, Symfony will also automatically choose the best Content-
Type header for the response. To restrict the formats supported by a given action, use the
requirements option of the @Route() annotation:
Listing 3-6 1 // src/AppBundle/Controller/DefaultController.php
2 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
3 use Symfony\Component\Routing\Annotation\Route;
4
5 // ...
6
7 /**
8 * @Route("/hello/{name}.{_format}",
9 * defaults = {"_format"="html"},
10 * requirements = { "_format" = "html|xml|json" },
11 * name = "hello"
12 * )
13 */
14 public function helloAction($name, $_format)
15 {
16 return $this->render('default/hello.'.$_format.'.twig', array(
17 'name' => $name
18 ));
19 }
The hello action will now match URLs like /hello/fabien.xml or /hello/fabien.json, but it
will show a 404 error if you try to get URLs like /hello/fabien.js, because the value of the _format
variable doesn't meet its requirements.
The redirectToRoute() method takes as arguments the route name and an optional array of
parameters and redirects the user to the URL generated with those arguments.
For 500 errors, just throw a regular PHP exception inside the controller and Symfony will transform it
into a proper 500 error page:
In a template, you can also access the Request object via the special app.request variable
automatically provided by Symfony:
You can also store "flash messages" that will auto-delete after the next request. They are useful when
you need to set a success message before redirecting the user to another page (which will then show the
message):
And you can display the flash message in the template like this:
New in version 3.3: The app.flashes() Twig function was introduced in Symfony 3.3. Prior, you had
to use app.session.flashBag().
Final Thoughts
That's all there is to it and I'm not even sure you have spent the full 10 minutes. You were briefly
introduced to bundles in the first part and all the features you've learned about so far are part of the core
FrameworkBundle. But thanks to bundles, everything in Symfony can be extended or replaced. That's the
topic of the next part of this tutorial.
You are my hero! Who would have thought that you would still be here after the first three parts? Your
efforts will be well rewarded soon. The first three parts didn't look too deeply at the architecture of
the framework. Because it makes Symfony stand apart from the framework crowd, let's dive into the
architecture now.
bin/
Executable files (e.g. bin/console).
src/
The project's PHP code.
tests/
Automatic tests (e.g. Unit tests).
var/
Generated files (cache, logs, etc.).
vendor/
The third-party dependencies.
web/
The web root directory.
The controller first bootstraps the application using a kernel class (AppKernel in this case). Then, it
creates the Request object using the PHP's global variables and passes it to the kernel. The last step is
to send the response contents returned by the kernel back to the user.
registerContainerConfiguration()
Loads the application configuration (more on this later).
Autoloading is handled automatically via Composer1, which means that you can use any PHP class
without doing anything at all! All dependencies are stored under the vendor/ directory, but this is just
a convention. You can store them wherever you want, globally on your server or locally in your projects.
1. https://getcomposer.org
In addition to the AppBundle that was already talked about, notice that the kernel also enables other
bundles that are part of Symfony, such as FrameworkBundle, DoctrineBundle, SwiftmailerBundle and
AsseticBundle.
Configuring a Bundle
Each bundle can be customized via configuration files written in YAML, XML, or PHP. Have a look at
this sample of the default Symfony configuration:
Each first level entry like framework, twig and swiftmailer defines the configuration for a specific
bundle. For example, framework configures the FrameworkBundle while swiftmailer configures the
SwiftmailerBundle.
Each environment can override the default configuration by providing a specific configuration file. For
example, the dev environment loads the config_dev.yml file, which loads the main configuration
(i.e. config.yml) and then modifies it to add some debugging tools:
Extending a Bundle
In addition to being a nice way to organize and configure your code, a bundle can extend another bundle.
Bundle inheritance allows you to override any existing bundle in order to customize its controllers,
templates, or any of its files.
Extending Bundles
If you follow these conventions, then you can use bundle inheritance to override files, controllers or
templates. For example, you can create a bundle - NewBundle - and specify that it overrides AppBundle.
When Symfony loads the AppBundle:Default:index controller, it will first look for the
DefaultController class in NewBundle and, if it doesn't exist, then look inside AppBundle. This
means that one bundle can override almost any part of another bundle!
Using Vendors
Odds are that your application will depend on third-party libraries. Those should be stored in the
vendor/ directory. You should never touch anything in this directory, because it is exclusively managed
by Composer. This directory already contains the Symfony libraries, the SwiftMailer library, the Doctrine
ORM, the Twig templating system and some other third party libraries and bundles.
When developing a web application, things can go wrong in many ways. The log files in the var/logs/
directory tell you everything about the requests and help you fix the problem quickly.
Final Thoughts
Call me crazy, but after reading this part, you should be comfortable with moving things around and
making Symfony work for you. Everything in Symfony is designed to get out of your way. So, feel free to
rename and move directories around as you see fit.
And that's all for the quick tour. From testing to sending emails, you still need to learn a lot to become
a Symfony master. Ready to dig into these topics now? Look no further - go to the official Symfony
Documentation and pick any topic you want.