Symfony 6 The Fast Track Fabien Potencier PDF Download
Symfony 6 The Fast Track Fabien Potencier PDF Download
download
https://ebookbell.com/product/symfony-6-the-fast-track-fabien-
potencier-47644076
https://ebookbell.com/product/the-definitive-guide-to-symfony-
francois-zaninotto-and-fabien-potencier-5551804
https://ebookbell.com/product/symfony2-essentials-wojciech-
bancer-6852966
https://ebookbell.com/product/symfony-13-web-application-development-
tim-bowler-wojciech-bancer-1232848
https://ebookbell.com/product/extending-symfony2-web-application-
framework-sebastien-armand-34415944
Mastering Symfony Sohail Salehi
https://ebookbell.com/product/mastering-symfony-sohail-salehi-5753830
https://ebookbell.com/product/a-year-with-symfony-writing-healthy-
reusable-symfony2-matthias-noback-5498662
https://ebookbell.com/product/a-year-with-symfony-writing-healthy-
reusable-symfony2-code-noback-11723322
https://ebookbell.com/product/a-gentle-introduction-to-
symfony-14-franois-zaninotto-fabien-potencier-2148262
Building Php Applications With Symfony Cakephp And Zend Framework 1st
Edition Bartosz Porbski
https://ebookbell.com/product/building-php-applications-with-symfony-
cakephp-and-zend-framework-1st-edition-bartosz-porbski-2324834
Symfony: The Fast Track
Fabien Potencier
https://fabien.potencier.org/
@fabpot
@fabpot
Symfony: The Fast Track
ISBN-13: 978-2-918390-37-4
Symfony SAS
6, rue des bateliers
92 110 Clichy
France
This work is licensed under the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
license (https://creativecommons.org/licenses/by-nc-sa/4.0/).
Below is a human-readable summary of (and not a substitute for) the license (https://creativecommons.org/
licenses/by-nc-sa/4.0/legalcode).
You are free to
Share — copy and redistribute the material in any medium or format
Adapt — remix, transform, and build upon the material
• Attribution: You must give appropriate credit, provide a link to the license, and indicate if changes were
made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses
you or your use.
• Non Commercial: You may not use the material for commercial purposes.
• Share Alike: If you remix, transform, or build upon the material, you must distribute your contributions
under the same license as the original.
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 Symfony 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 at support@symfony.com. This book is continuously
updated based on user feedback.
Locale en
v
Step 27: Building an SPA............................................................................... 269
Step 28: Localizing an Application ................................................................. 287
Step 29: Managing Performance .................................................................... 301
Step 30: Discovering Symfony Internals.......................................................... 311
Step 31: Using Redis to Store Sessions ............................................................ 321
Step 32: Using RabbitMQ as a Message Broker............................................... 325
Step 33: What’s Next? ................................................................................... 331
vi
Table of Contents
Step 0: What is it about?.................................................................................. 21
ix
Step 4: Adopting a Methodology ...................................................................... 45
4.1: Implementing a Git Strategy.................................................................. 45
4.2: Deploying to Production Continuously................................................... 46
x
8.7: Migrating the Database ........................................................................ 79
8.8: Updating the Local Database ................................................................ 80
8.9: Updating the Production Database ........................................................ 80
xi
13.3: Generating Slugs .............................................................................. 124
13.4: Defining a Complex Lifecycle Callback .............................................. 125
13.5: Configuring a Service in the Container ............................................... 126
13.6: Using Slugs in the Application ........................................................... 127
xii
17.2: Writing Functional Tests for Controllers ............................................ 165
17.3: Configuring the Test Environment ..................................................... 167
17.4: Working with a Test Database .......................................................... 167
17.5: Defining Fixtures.............................................................................. 168
17.6: Loading Fixtures .............................................................................. 170
17.7: Crawling a Website in Functional Tests.............................................. 171
17.8: Submitting a Form in a Functional Test.............................................. 172
17.9: Reloading the Fixtures ...................................................................... 174
17.10: Automating your Workflow with a Makefile ..................................... 174
17.11: Resetting the Database after each Test ............................................. 175
17.12: Using a real Browser for Functional Tests......................................... 177
17.13: Choosing the Right Test Type .......................................................... 178
17.14: Running Black Box Functional Tests with Blackfire........................... 178
xiii
20.7: Accessing the Webmail...................................................................... 205
20.8: Managing Long-Running Scripts........................................................ 207
20.9: Sending Emails Asynchronously......................................................... 207
20.10: Testing Emails ................................................................................ 208
20.11: Sending Emails on Platform.sh ........................................................ 209
xiv
Step 25: Notifying by all Means ..................................................................... 245
25.1: Sending Web Application Notifications in the Browser ........................ 245
25.2: Notifying Admins by Email ............................................................... 249
25.3: Chatting with Admins ....................................................................... 252
25.4: Going Asynchronous across the Board ............................................... 258
25.5: Notifying Users by Email .................................................................. 259
xv
29.1: Introducing Blackfire ........................................................................ 302
29.2: Setting Up the Blackfire Agent on Docker........................................... 303
29.3: Fixing a non-working Blackfire Installation ........................................ 304
29.4: Configuring Blackfire in Production ................................................... 304
29.5: Configuring Varnish for Blackfire ...................................................... 305
29.6: Profiling Web Pages.......................................................................... 306
29.7: Profiling API Resources..................................................................... 307
29.8: Comparing Performance ................................................................... 307
29.9: Writing Black Box Functional Tests ................................................... 307
29.10: Automating Performance Checks ..................................................... 309
xvi
Acknowledgments
The last time I wrote a book about Symfony was exactly 10 years ago. It
was about Symfony 1.4. I have never written about Symfony since then!
I was so excited to write again about Symfony that I finished the first draft
in a week. But the version you are reading took way more time. Writing
a book takes a lot of time and energy. From the cover design to the page
layout. From code tweaks to peer reviews. It is almost never finished.
You can always improve a section, enhance some piece of code, fix some
typos, or rewrite an explanation to make it shorter and better.
Writing a book is a journey that you don’t want to do alone. Many people
contributed directly or indirectly. Thank you all!
I want to sincerely thank all the great people who spent a lot of time
reviewing the content to spot typos and improve the content; some even
helped me write some of the code snippets:
xvii
Translators
The official Symfony documentation is only available in English. We had
some translations in the past but we decided to stop providing them as
they were always out of sync. And outdated documentation is probably
worse than no documentation at all.
However, translating a book like the one you are currently reading is
more manageable as I tried to write about features that won’t change
much over time. This is why the book contents should stay quite stable
over time.
As you can imagine, translating more than 300 pages is a huge amount
of work, and I want to thank all the people who helped translating this
book:
xviii
Company Backers
https://sensiolabs.com/
https://platform.sh/
https://qossmic.com/
https://blackfire.io/ https://les-tilleuls.coop/
xix
Family Love
Family support is everything. A big thank-you to my wife, Hélène and
my two wonderful children, Thomas and Lucas, for their continuous
support.
xx
Step 0
What is it about?
21
time to follow everything happening in the community. I know first hand
as I would not pretend that I can follow everything myself. Far from it.
And it is not just about new ways of doing things. It is also about
new components: HTTP client, Mailer, Workflow, Messenger. They are
game changers. They should change the way you think about a Symfony
application.
I also feel the need for a new book as the Web has evolved a lot. Topics
like APIs, SPAs, containerization, Continuous Deployment, and many
others should be discussed now.
Your time is precious. Don’t expect long paragraphs, nor long
explanations about core concepts. The book is more about the journey.
Where to start. Which code to write. When. How. I will try to generate
some interest on important topics and let you decide if you want to learn
more and dig further.
I don’t want to replicate the existing documentation either. Its quality
is excellent. I will reference the documentation copiously in the “Going
Further” section at the end of each step/chapter. Consider this book as a
list of pointers to more resources.
The book describes the creation of an application, from scratch to
production. We won’t develop everything to make it production ready
though. The result won’t be perfect. We will take shortcuts. We might
even skip some edge-case handling, validation or tests. Best practices
won’t be respected all the time. But we are going to touch on almost every
aspect of a modern Symfony project.
While starting to work on this book, the very first thing I did was code
the final application. I was impressed with the result and the velocity I
was able to sustain while adding features, with very little effort. That’s
thanks to the documentation and the fact that Symfony knows how to get
out of your way. I am sure that Symfony can still be improved in many
ways (and I have taken some notes about possible improvements), but the
developer experience is way better than a few years ago. I want to tell the
world about it.
The book is divided into steps. Each step is sub-divided into sub-steps.
They should be fast to read. But more importantly, I invite you to code as
you read. Write the code, test it, deploy it, tweak it.
22
Last, but not least, don’t hesitate to ask for help if you get stuck. You
might hit an edge case or a typo in the code you wrote might be difficult
to find and fix. Ask questions. We have a wonderful community on Slack
and GitHub.
Ready to code? Enjoy!
23
Step 1
Checking your Work
Environment
Before starting to work on the project, we need to check that you have
a good working environment. It is very important. The developers tools
we have at our disposal today are very different from the ones we had 10
years ago. They have evolved a lot, for the better. It would be a shame to
not leverage them. Good tools can get you a long way.
Please, don’t skip this step. Or at least, read the last section about the
Symfony CLI.
1.1 A Computer
You need a computer. The good news is that it can run on any popular
OS: macOS, Windows, or Linux. Symfony and all the tools we are going
to use are compatible with each of these.
25
1.2 Opinionated Choices
I want to move fast with the best options out there. I made opinionated
choices for this book.
PostgreSQL is going to be our choice for everything: from database to
queues, from cache to session storage. For most projects, PostgreSQL is
the best solution, scale well, and allows to simplify the infrastructure with
only one service to manage.
At the end of the book, we will learn how to use RabbitMQ for queues
and Redis for sessions.
1.3 IDE
You can use Notepad if you want to. I would not recommend it though.
I used to work with Textmate. Not anymore. The comfort of using
a “real” IDE is priceless. Auto-completion, use statements added and
sorted automatically, jumping from one file to another are a few features
that will boost your productivity.
I would recommend using Visual Studio Code or PhpStorm. The former is
free, the latter is not but has a better integration with Symfony (thanks to
the Symfony Support Plugin). It is up to you. I know you want to know
which IDE I am using. I am writing this book in Visual Studio Code.
1.4 Terminal
We will switch from the IDE to the command line all the time. You can
use your IDE’s built-in terminal, but I prefer to use a real one to have
more space.
Linux comes built-in with Terminal. Use iTerm2 on macOS. On
Windows, Hyper works well.
26
1.5 Git
For version control, we will use Git as everybody is using it now.
On Windows, install Git bash.
Be sure you know how to do the common operations like running git
clone, git log, git show, git diff, git checkout, …
1.6 PHP
We will use Docker for services, but I like to have PHP installed on my
local computer for performance, stability, and simplicity reasons. Call me
old school if you like, but the combination of a local PHP and Docker
services is the perfect combo for me.
Use PHP 8.1 and check that the following PHP extensions are installed
or install them now: intl, pdo_pgsql, xsl, amqp, gd, openssl, sodium.
Optionally install redis, curl, and zip as well.
You can check the extensions currently enabled via php -m.
We also need php-fpm if your platform supports it, php-cgi works as well.
1.7 Composer
Managing dependencies is everything nowadays with a Symfony project.
Get the latest version of Composer, the package management tool for
PHP.
If you are not familiar with Composer, take some time to read about it.
You don’t need to type the full command names: composer req does
the same as composer require, use composer rem instead of composer
remove, …
27
1.8 NodeJS
We won’t write much JavaScript code, but we will use JavaScript/NodeJS
tools to manage our assets. Check that you have the NodeJS installed.
Check that your computer has all needed requirements by running the
following command:
$ symfony book:check-requirements
If you want to get fancy, you can also run the Symfony proxy. It is optional
but it allows you to get a local domain name ending with .wip for your
project.
When executing a command in a terminal, we will almost always prefix it
with symfony like in symfony composer instead of just composer, or symfony
console instead of ./bin/console.
28
The main reason is that the Symfony CLI automatically sets some
environment variables based on the services running on your machine
via Docker. These environment variables are available for HTTP requests
because the local web server injects them automatically. So, using symfony
on the CLI ensures that you have the same behavior across the board.
Moreover, the Symfony CLI automatically selects the “best” possible PHP
version for the project.
29
Step 2
Introducing the Project
31
The project will contain several applications. A traditional web application
with an HTML frontend, an API, and an SPA for mobile phones. How
does that sound?
32
One of the great benefit of using a framework is the small amount of code
needed to develop such a project:
• 20 PHP classes under src/ for the website;
• 550 PHP Logical Lines of Code (LLOC) as reported by PHPLOC;
• 40 lines of configuration tweaks in 3 files (via attributes and YAML),
mainly to configure the backend design;
• 20 lines of development infrastructure configuration (Docker);
• 100 lines of production infrastructure configuration (Platform.sh);
• 5 explicit environment variables.
34
about developing a website. As each chapter depends on the previous
ones, a change might have consequences in all following chapters.
The good news is that the Git repository for this book is automatically
generated from the book content. You read that right. I like to automate
everything, so there is a script whose job is to read the book and create
the Git repository. There is a nice side-effect: when updating the book,
the script will fail if the changes are inconsistent or if I forget to update
some instructions. That’s BDD, Book Driven Development!
Like for cloning the repository, we are not using git checkout but symfony
book:checkout. The command ensures that whatever the state you are
currently in, you end up with a functional website for the step you ask for.
Be warned that all data, code, and containers are removed by this
operation.
You can also check out any substep:
$ symfony book:checkout 10.2
Again, I highly recommend you code yourself. But if you get stuck, you
can always compare what you have with the content of the book.
Not sure that you got everything right in substep 10.2? Get the diff:
$ git diff step-10-1...step-10-2
35
# And for the very first substep of a step:
$ git diff step-9...step-10-1
You can also browse diffs, tags, and commits directly on GitHub. This is
a great way to copy/paste code if you are reading a paper book!
36
Step 3
Going from Zero to Production
I like to go fast. I want our little project to be live as fast as possible. Like
now. In production. As we haven’t developed anything yet, we will start
by deploying a nice and simple “Under construction” page. You will love
it!
Spend some time trying to find the ideal, old fashioned, and animated
“Under construction” GIF on the Internet. Here is the one I’m going to
use:
37
3.1 Initializing the Project
Create a new Symfony project with the symfony CLI tool we have
previously installed together:
$ symfony new guestbook --version=6.2 --php=8.1 --webapp --docker --cloud
$ cd guestbook
This command is a thin wrapper on top of Composer that eases the creation
of Symfony projects. It uses a project skeleton that includes the bare
minimum dependencies; the Symfony components that are needed for
almost any project: a console tool and the HTTP abstraction needed to
create Web applications.
As we are creating a fully-featured web application, we have added a few
options that will make our life easier:
• --webapp: By default, an application with the fewest possible
dependencies is created. For most web projects, it is recommended
to use the webapp package on top. It contains most of the packages
needed for “modern” web applications. The webapp package adds a lot
of Symfony packages, including Symfony Messenger and PostgreSQL
via Doctrine.
• --docker: On your local machine, we will use Docker to manage
services like PostgreSQL. This option enables Docker so that Symfony
will automatically add Docker services based on the required
packages (a PostgreSQL service when adding the ORM or a mail
catcher when adding Symfony Mailer for instance).
• --cloud: If you want to deploy your project on Platform.sh, this
option automatically generates a sensible Platform.sh configuration.
Platform.sh is the preferred and simplest way to deploy testing,
staging, and production Symfony environments in the cloud.
If you have a look at the GitHub repository for the skeleton, you will
notice that it is almost empty. Just a composer.json file. But the guestbook
directory is full of files. How is that even possible? The answer lies in
the symfony/flex package. Symfony Flex is a Composer plugin that hooks
into the installation process. When it detects a package for which it has a
38
recipe, it executes it.
The main entry point of a Symfony Recipe is a manifest file that describes
the operations that need to be done to automatically register the package
in a Symfony application. You never have to read a README file to
install a package with Symfony. Automation is a key feature of Symfony.
As Git is installed on our machine, symfony new also created a Git
repository for us and it added the very first commit.
Have a look at the directory structure:
├── bin/
├── composer.json
├── composer.lock
├── config/
├── public/
├── src/
├── symfony.lock
├── var/
└── vendor/
The bin/ directory contains the main CLI entry point: console. You will
use it all the time.
The config/ directory is made of a set of default and sensible
configuration files. One file per package. You will barely change them,
trusting the defaults is almost always a good idea.
The public/ directory is the web root directory, and the index.php script
is the main entry point for all dynamic HTTP resources.
The src/ directory hosts all the code you will write; that’s where you will
spend most of your time. By default, all classes under this directory use
the App PHP namespace. It is your home. Your code. Your domain logic.
Symfony has very little to say there.
The var/ directory contains caches, logs, and files generated at runtime by
the application. You can leave it alone. It is the only directory that needs
to be writable in production.
The vendor/ directory contains all packages installed by Composer,
including Symfony itself. That’s our secret weapon to be more
productive. Let’s not reinvent the wheel. You will rely on existing libraries
to do the hard work. The directory is managed by Composer. Never
39
touch it.
That’s all you need to know for now.
The server started on the first available port, starting with 8000. As a
shortcut, open the website in a browser from the CLI:
$ symfony open:local
Your favorite browser should take the focus and open a new tab that
displays something similar to the following:
40
••• /
••• /images/under-construction.gif
41
great step forward. And you know the motto: deploy early and often.
You can host this application on any provider supporting PHP… which
means almost all hosting providers out there. Check a few things though:
we want the latest PHP version and the possibility to host services like a
database, a queue, and some more.
I have made my choice, it’s going to be Platform.sh. It provides everything
we need and it helps fund the development of Symfony.
As we used the --cloud option when we created the project, Platform.sh
has already been initialized with a few files needed by Platform.sh, namely
.platform/services.yaml, .platform/routes.yaml, and
.platform.app.yaml.
Then, deploy:
$ symfony cloud:deploy
The code is deployed by pushing the Git repository. At the end of the
command, the project will have a specific domain name you can use to
access it.
Check that everything worked fine:
42
$ symfony cloud:url -1
Going Further
• The repositories for the official Symfony recipes and for the recipes
contributed by the community, where you can submit your own
recipes;
• The Symfony Local Web Server;
• The Platform.sh documentation.
43
Step 4
Adopting a Methodology
Teaching is about repeating the same thing again and again. I won’t do
that. I promise. At the end of each step, you should do a little dance and
save your work. It is like Ctrl+S but for a website.
You can safely add “everything” as Symfony manages a .gitignore file for
you. And each package can add more configuration. Have a look at the
current content:
.gitignore
###> symfony/framework-bundle ###
/.env.local
/.env.local.php
45
/.env.*.local
/config/secrets/prod/prod.decrypt.private.php
/public/bundles/
/var/
/vendor/
###< symfony/framework-bundle ###
The funny strings are markers added by Symfony Flex so that it knows
what to remove if you decide to uninstall a dependency. I told you, all the
tedious work is done by Symfony, not you.
It could be nice to push your repository to a server somewhere. GitHub,
GitLab, or Bitbucket are good choices.
46
Step 5
Troubleshooting Problems
47
••• /
The first thing you might notice is the 404 in red. Remember that this
page is a placeholder as we have not defined a homepage yet. Even if the
default page that welcomes you is beautiful, it is still an error page. So
the correct HTTP status code is 404, not 200. Thanks to the web debug
toolbar, you have the information right away.
If you click on the small exclamation point, you get the “real” exception
message as part of the logs in the Symfony profiler. If you want to see the
stack trace, click on the “Exception” link on the left menu.
Whenever there is an issue with your code, you will see an exception page
like the following that gives you everything you need to understand the
issue and where it comes from:
48
••• //
Take some time to explore the information inside the Symfony profiler by
clicking around.
Logs are also quite useful in debugging sessions. Symfony has a
convenient command to tail all the logs (from the web server, PHP, and
your application):
$ symfony server:log
49
support for three, but you can add as many as you like: dev, prod, and
test. All environments share the same code, but they represent different
configurations.
For instance, all debugging tools are enabled in the dev environment. In
the prod one, the application is optimized for performance.
Switching from one environment to another can be done by changing the
APP_ENV environment variable.
When you deployed to Platform.sh, the environment (stored in APP_ENV)
was automatically switched to prod.
$ export APP_ENV=dev
Using real environment variables is the preferred way to set values like
APP_ENV on production servers. But on development machines, having to
define many environment variables can be cumbersome. Instead, define
them in a .env file.
A sensible .env file was generated automatically for you when the project
was created:
.env
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=c2927f273163f7225a358e3a1bbbed8a
#TRUSTED_PROXIES=127.0.0.1,127.0.0.2
#TRUSTED_HOSTS='^localhost|example\.com$'
###< symfony/framework-bundle ###
Any package can add more environment variables to this file thanks to
their recipe used by Symfony Flex.
The .env file is committed to the repository and describes the default
values from production. You can override these values by creating a
50
Random documents with unrelated
content Scribd suggests to you:
Long therefore, may English men and women play together, since
thereby they will know one another, respect one another and help
one another more thoroughly.
CHAPTER XII
THE ENGLISHWOMAN IN PARLIAMENT
FOOTNOTES:
1 See The Education of Henry Adams, p. 442
2 Even M. Marcel Proust’s remarkable picture of modern
“jeunes filles” in his masterpiece of discursion “A l’ombre des
jeunes filles en fleurs” does not convince me that flappers exist in
France.
*** END OF THE PROJECT GUTENBERG EBOOK THE GOOD
ENGLISHWOMAN ***
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookbell.com