Symfony Tutorial
Symfony Tutorial
Symfony Tutorial
Audience
This tutorial has been prepared for beginners who want to learn the fundamental concenpts
of Symfony framework. The readers will get enough understanding on how to create and
develop a website using Symfony.
Prerequisites
Before proceeding with the various types of components given in this tutorial, it is being
assumed that the readers are already aware about what a Framework is. In addition to
this, it will also be very helpful if you have a sound knowledge on HTML, PHP, and the
OOPS concepts.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Symfony
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
1. SYMFONY ─ INTRODUCTION................................................................................................ 1
Web Framework...................................................................................................................................... 7
ii
Symfony
Controller .............................................................................................................................................. 40
FrontController ..................................................................................................................................... 44
Annotations .......................................................................................................................................... 46
Templates ............................................................................................................................................. 51
Layouts.................................................................................................................................................. 58
Assets .................................................................................................................................................... 58
Form Fields............................................................................................................................................ 71
iii
Symfony
PHPUnit............................................................................................................................................... 114
Debug.................................................................................................................................................. 119
iv
Symfony
v
1. Symfony ─ Introduction Symfony
A PHP web framework is a collection of classes, which helps to develop a web application.
Symfony is an open-source MVC framework for rapidly developing modern web
applications. Symfony is a full-stack web framework. It contains a set of reusable PHP
components. You can use any Symfony components in applications, independently from
the framework.
Symfony has a huge amount of functionality and active community. It has a flexible
configuration using YAML, XML, or annotations. Symfony integrates with an independent
library and PHP Unit. Symfony is mainly inspired by Ruby on Rails, Django, and Spring
web application frameworks. Symfony components are being used by a lot of open source
projects that include Composer, Drupal, and phpBB.
Symfony’s well-organized structure, clean code, and good programming practices make
web development easier. Symfony is very flexible, used to build micro-sites and handle
enterprise applications with billions of connections.
Symfony offers a lot of flexibility to developers. It has great features for debugging, code
readability, and developing extensible programs.
1
Symfony
Symfony is a full-stack web framework; it is a very effective tool for creating web
applications. Numerous companies offer Symfony services to clients.
Following are some of the benefits that you get by using the Symfony Framework.
Extremely mature templating engine and quickly delivers content to the users.
Compatible and extensible – Programmers can easily extend all framework classes.
2
2. Symfony ─ Installation Symfony
This chapter explains how to install Symfony framework on your machine. Symfony
framework installation is very simple and easy. You have two methods to create
applications in Symfony framework. First method is using Symfony Installer, an application
to create a project in Symfony framework. Second method is composer-based installation.
Let’s go through each of the methods one by one in detail in the following sections.
System Requirements
Before moving to installation, you require the following system requirements.
We will use PHP built-in development web server for this tutorial.
Symfony Installer
Symfony Installer is used to create web applications in Symfony framework. Now, let’s
configure the Symfony installer using the following command.
3
Symfony
Syntax
symfony new app_name
Here, app_name is your new application name. You can specify any name you want.
Example
symfony new HelloWorld
After executing the above command, you will see the following response.
Downloading Symfony...
……………………………………………………………
……………………………………………………………
Preparing project...
This command creates a new directory called “firstapp/“ that contains an empty project of
Symfony framework latest version.
4
Symfony
Composer-based Installation
You can create Symfony applications using the Composer. Hopefully, you have installed
the composer on your machine. If the composer is not installed, download and install it.
If you need to specify a specific version, you can specify in the above command.
cd HelloWorld
php bin/console server:run
After executing the above command, open your browser and request the url
http://localhost:8000/. It produces the following result.
Result
5
3. Symfony ─ Architecture Symfony
Symfony is basically a collection of high quality components and bundles. Components are
collection of classes providing a single core functionality. For example, Cache component
provides cache functionality, which can be added to any application. Components are
building blocks of a Symfony application. Symfony has 30+ high quality components,
which are used in many PHP framework such as Laravel, Silex, etc.
Bundles are similar to plugin but easy to create and easy to use. Actually, a Symfony
application is itself a bundle composed of other bundles. A single bundle can use any
number of Symfony component and also third-party components to provide features such
as Webframework, database access, etc. Symfony core web-framework is a bundle called
FrameworkBundle and there is a bundle called FrameworkExtraBundle, which provides
more sophisticated options to write a web application.
The relationship between the Components, Bundles, and Symfony application is specified
in the following diagram.
6
Symfony
Web Framework
Symfony is mainly designed to write high-quality web application with relative ease. It
provides various options to write different types of web application from simple web site
to advanced REST based web services. Symfony provides web framework as separate
bundles. The common bundles used in Symfony web framework are as follows:
FrameworkBundle
FrameworkExtraBundle
DoctrineBundle
Symfony web framework provides all the high-level features required for an enterprise-
grade application. Following is a simple workflow of Symfony web application.
Step 1: The user sends a request to the application through the browser, say
http://www.symfonyexample.com/index.
Step 2: The browser will send a request to the web server, say Apache web server.
Step 3: The web server will forward the request to the underlying PHP, which in turn
sends it to Symfony web framework.
7
Symfony
Step 4: HttpKernel is the core component of the Symfony web framework. HttpKernel
resolves the controller of the given request using Routing component and forward the
request to the target controller.
Step 5: All the business logic takes place in the target controller.
Step 6: The controller will interact with Model, which in turn interacts with Datasource
through Doctrine ORM.
Step 7: Once the controller completes the process, it either generates the response itself
or through View Engine, and sends it back to the web server.
Step 8: Finally, the response will be sent to the requested browser by the web server.
8
4. Symfony ─ Components Symfony
As discussed earlier, Symfony components are standalone PHP library providing a specific
feature, which can be used in any PHP application. Useful new components are being
introduced in each and every release of Symfony. Currently, there are 30+ high quality
components in Symfony framework. Let us learn about the usage of Symfony components
in this chapter.
cd /path/to/project/dir
composer require symfony/<component_name>
Let us create a simple php application and try to install Filesystem component.
cd /path/to/dev/folder
mdkir filesystem-example
cd filesystem-example
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
$fs = new Filesystem();
try {
$fs->mkdir('./sample-dir');
$fs->touch('./sample-dir/text.txt');
} catch (IOExceptionInterface $e) {
echo $e;
}
?>
9
Symfony
The first line is very important, which loads all the necessary classes from all the
components installed using the Composer command. The next lines use the Filesystem
class.
Step 4: Run the application using the following command and it will create a new folder
sample-dir and a file test.txt under it.
php main.php
Filesystem
Filesystem component provides a basic system command related to files and directories
such as file creation, folder creation, file existence, etc. Filesystem component can be
installed using the following command.
Finder
Finder component provides fluent classes to find files and directories in a specified path.
It provides an easy way to iterate over the files in a path. Finder component can be
installed using the following command.
Console
Console component provides various options to easily create commands, which can be
executed in a terminal. Symfony uses the Command component extensively to provide
various functionalities such as creating a new application, creating a bundle, etc. Even the
PHP build in web server can be invoked using Symfony command, php bin/console
server:run as seen in the installation section. The Console component can be installed
using the following command.
Let us create a simple application and create a command, HelloCommand using the
Console component and invoke it.
cd /path/to/project
composer require symfony/console
10
Symfony
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Console\Application;
$app = new Application();
$app->run();
?>
Step 3: Run the application, php main.php, which will produce the following result.
Console Tool
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal
output, 2 for more verbose output and 3 for debug
Available commands:
help Displays help for a command
list Lists commands
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
11
Symfony
Step 5: Create a function configure() and set name, description, and help text.
Step 6: Create an input argument, user for the command and set as mandatory.
12
Symfony
Step 8: Use InputArgument to get the user details entered by the user and print it to
the console using OutputArgument.
Step 9: Register the HelloCommand into the application using the add method of
Application class.
$app->add(new HelloCommand());
<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
13
Symfony
}
}
Step 10: Now, execute the application using the following command and the result will
be Hello, Jon as expected.
Symfony comes with a pre-built binary called console in the bin directory of any Symfony
web application, which can be used to invoke the commands in an application.
14
Symfony
15