Hướng dẫn dùng symfony tutorialspoint trong PHP

Symfony is an open-source PHP web application framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Symfony is sponsored by SensioLabs. It was developed by Fabien Potencier in 2005. This tutorial will give you a quick introduction to Symfony framework and make you comfortable with its various components.

Audience

This tutorial has been prepared for beginners who want to learn the fundamental concepts 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.


Symfony - Introduction

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.

The Symfony framework consists of several components, such as the HttpFoundation component that understands HTTP and offers a nice request and response object used by the other components. Others are merely helper components, such as the Validator, that helps to validate data. Kernel component is the heart of the system. Kernel is basically the ‘main class’ that manages the environment and has the responsibility of handling a http request.

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 Framework - Features

Symfony is designed to optimize the development of web applications and grows in features with every release.

Some of the salient features of Symfony Framework is as follows −

  • Model-View-Controller based system
  • High-performance PHP framework
  • Flexible URI routing
  • Code reusable and easier to maintain
  • Session management
  • Error logging
  • Full-featured database classes with support for several platforms
  • Supports a huge and active community
  • Set of decoupled and reusable components
  • Standardization and interoperability of applications
  • Security against cross-site request forgery and other attacks
  • Twig template engine

Symfony offers a lot of flexibility to developers. It has great features for debugging, code readability, and developing extensible programs.

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.

  • Microframework − Symfony can be used to develop a specific functionality. You don’t need to redevelop or install the entire framework.

  • Reduces development time overhead.

  • Extremely mature templating engine and quickly delivers content to the users.

  • Compatible and extensible − Programmers can easily extend all framework classes.

Symfony Framework - Applications

Symfony components can be used as a part of other applications such as Drupal, Laravel, phpBB, Behat, Doctrine, and Joomla.

  • Drupal 8 − Drupal is an open source content management PHP framework. Drupal 8 uses core layers of Symfony and extends it to provide support for Drupal modules.

  • Thelia − Thelia is a Symfony-based e-commerce solution. Initially, Thelia was written in PHP code and MySQL, however, it was lagging to produce faster applications. To overcome this drawback, Thelia integrated with Symfony to develop the applications in a customizable way.

  • Dailymotion − Dailymotion is one of the world's largest independent video entertainment website based in France. Once they decided to migrate open source framework with a large community, Dailymotion developers decided to use Symfony components features for its flexibility.

Symfony - Installation

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.

  • Web server [Any one of the following]
    • WAMP [Windows]
    • LAMP [Linux]
    • XAMP [Multi-platform]
    • MAMP [Macintosh]
    • Nginx [Multi-platform]
    • Microsoft IIS [Windows]
    • PHP built-in development web server [Multi-platform]
  • Operating System: Cross-platform
  • Browser Support: IE [Internet Explorer 8+], Firefox, Google Chrome, Safari, Opera
  • PHP Compatibility: PHP 5.4 or later. To get the maximum benefit, use the latest version.

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.

$ sudo mkdir -p /usr/local/bin 
$ sudo curl -LsS //symfony.com/installer -o /usr/local/bin/symfony 
$ sudo chmod a+x /usr/local/bin/symfony

Now, you have installed Symfony installer on your machine.

Create Your First Symfony Application

Following syntax is used to create a Symfony application in the latest version.

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...  

0 B/5.5 MiB ░░░░░░░░░░░  
……………………………………………………………  
……………………………………………………………   
Preparing project...  
✔  Symfony 3.2.7 was successfully installed. Now you can:  
   * Change your current directory to /Users/../workspace/firstapp  
   * Configure your application in app/config/parameters.yml file.  
   * Run your application: 
      1. Execute the php bin/console server:run command. 
      2. Browse to the //localhost:8000 URL.  
   * Read the documentation at //symfony.com/doc 

This command creates a new directory called “firstapp/“ that contains an empty project of Symfony framework latest version.

Install Specific Version

If you need to install a specific Symfony version, use the following command.

symfony new app_name 2.8 
symfony new app_name 3.1

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.

The following command is used to create a project using the composer.

$ composer create-project symfony/framework-standard-edition app_name

If you need to specify a specific version, you can specify in the above command.

Running the Application

Move to the project directory and run the application using the following command.

cd HelloWorld 
php bin/console server:run 

After executing the above command, open your browser and request the url //localhost:8000/. It produces the following result.

Result

Symfony - Architecture

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.

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 is based on Model-View-Controller [MVC] architecture. Model represents the structure of our business entities. View shows the models to the user in the best possible way depending on the situation. Controller handles all the request from the user, does the actual work by interacting with Model and finally provides the View with the necessary data to show it to the user.

Symfony web framework provides all the high-level features required for an enterprisegrade application. Following is a simple workflow of Symfony web application.

The workflow consists of the following steps.

Step 1 − The user sends a request to the application through the browser, say //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.

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.

Symfony - Components

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.

Installing a Symfony Component

Symfony components can be installed easily using the composer command. Following generic command can be used to install any Symfony component.

cd /path/to/project/dir 
composer require symfony/ 

Let us create a simple php application and try to install Filesystem component.

Step 1 − Create a folder for the application, filesystem-example

cd /path/to/dev/folder 
mdkir filesystem-example 
cd filesystem-example 

Step 2 − Install Filesystem component using the following command.

composer require symfony/filesystem  

Step 3 − Create a file main.php and enter the following code.

  

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

Details of Symfony Components

Symfony provides components ranging from simple feature, say file system to advanced feature, say events, container technology, and dependency injection. Let us know about all the components one by one in the following sections.

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.

composer require symfony/filesystem

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.

composer require symfony/finder

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.

composer require symfony/console

Let us create a simple application and create a command, HelloCommand using the Console component and invoke it.

Step 1 − Create a project using the following command.

cd /path/to/project 
composer require symfony/console 

Step 2 − Create a file main.php and include the following code.

 

Application class sets up the necessary functionality of a bare-bone console application.

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

Step 4 − Create a class called HelloCommand extending Command class in the main.php itself.

use Symfony\Component\Console\Command\Command; 
use Symfony\Component\Console\Input\InputInterface; 
use Symfony\Component\Console\Output\OutputInterface; 
use Symfony\Component\Console\Input\InputArgument;

class HelloCommand extends Command { 
}

The application uses following four classes available in Command component.

  • Command − Used to create a new command

  • InputInterface − Used to set user inputs

  • InputArgument − Used to get user inputs

  • OutputInterface − Used to print output to the console

step 5 − Create a function configure[] and set name, description, and help text.

protected function configure[] { 
   $this 
      ->setName['app:hello'] 
      ->setDescription['Sample command, hello'] 
      ->setHelp['This command is a sample command'] 
} 

step 6 − Create an input argument, user for the command and set as mandatory.

protected function configure[] { 
   $this 
      ->setName['app:hello'] 
      ->setDescription['Sample command, hello'] 
      ->setHelp['This command is a sample command'] 
      ->addArgument['name', InputArgument::REQUIRED, 'name of the user']; 
}

step 7 − Create a function execute[] with two arguments InputArgument and OutputArgument.

protected function execute[InputInterface $input, OutputInterface $output] { 
}

step 8 − Use InputArgument to get the user details entered by the user and print it to the console using OutputArgument.

protected function execute[InputInterface $input, OutputInterface $output] { 
   $name = $input->getArgument['name']; 
   $output->writeln['Hello, ' . $name]; 
}

step 9 − Register the HelloCommand into the application using the add method of Application class.

$app->add[new HelloCommand[]]; 

The complete application is as follows.

      

Step 10 − Now, execute the application using the following command and the result will be Hello, Jon as expected.

php main.php app:hello Jon

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.

Process

Process component provides options to run any system command in a sub-process, in a safe and efficient manner. Process component can be installed using the following command.

composer require symfony/process

ClassLoader

ClassLoader component provides implementation for both PSR-0 and PSR-4 class loader standard. It can be used to auto-load the classes. It will be depreciated in the near future. Composer-based class loader is preferred over this component. ClassLoader component can be installed using the following command.

composer require symfony/class-loader

PropertyAccess

PropertyAccess component provides various options to read and write an object and array details using the string notation. For example, an array Product with key price can be accessed dynamically using [price] string.

$product = array[ 
   'name' => 'Cake' 
   'price' => 10 
];  
var priceObj = $propertyAccesserObj->getValue[$product, '[price]'];

PropertyAccess component can be installed using the following command.

composer require symfony/property-access 

PropertyInfo

PropertyInfo component is similar to PropertyAccess component, however it only works with PHP objects and provides much more functionality.

class Product { 
   private $name = 'Cake'; 
   private $price = 10;  
   
   public function getName[] { 
      return $this->name; 
   }  
   public function getPrice[] { 
      return $this->price; 
   } 
}  
$class = Product::class; 
$properties = $propertyInfoObj->getProperties[$class];  
/* 
   Example Result 
   -------------- 
   array[2] { 
      [0] => string[4] "name" 
      [1] => string[5] "price" 
   } 
*/

PropertyInfo component can be installed using the following command.

composer require symfony/property-info

EventDispatcher

EventDispatcher component provides an event-based programming in PHP. It enables the objects to communicate with each other by dispatching events and listening to them. We will learn how to create event and listen to them in the Events and Event Listener chapter.

EventDispatcher component can be installed using the following command.

composer require symfony/event-dispatcher

DependencyInjection

DependencyInjection component provides an easy and efficient mechanism to create an object with its dependency. When a project grows, it features a lot of classes with deep dependency, which needs to be handled correctly. Otherwise, the project fails. DependencyInjection provides a simple and robust container to handle the dependency. We will learn about the containers and the dependency injection concept in Service Container chapter.

DependencyInjection component can be installed using the following command.

composer require symfony/dependency-injection

Serializer

Serializer component provides an option to convert a PHP object into a specific format such as XML, JSON, Binary, etc., and then allows it to convert it back into an original object without any data loss.

Serializer component can be installed using the following command.

composer require symfony/serializer

Config

Config component provides options to load, parse, read, and validate configurations of type XML, YAML, PHP and ini. It provides various options to load configuration details from database as well. This is one of the important components useful in configuring web application in a clear and concise manner. Config component can be installed using the following command.

composer require symfony/config

ExpressionLanguage

ExpessionLanguage component provides a full-fledged expression engine. Expressions are one-liner intended to return a value. The expression engine enables to easily compile, parse, and get the value from an expression. It enables one or more expression to be used in a configuration environment [file] by a non-PHP programmer, say a system administrator. ExpressionLanguage component can be installed using the following command.

composer require symfony/expression-language

OptionsResolver

OptionsResolver component provides a way to validate the option system used in our system. For example, database setting is placed in an array, dboption with host, username, password, etc., as keys. You need to validate the entries before using it to connect to a database. OptionsResolver simplifies this task by providing a simple class OptionsResolver and a method resolver, which resolves the database setting and if there is any validation issue, it will report it.

$options = array[ 
   'host'     => '', 
   'username' => '', 
   'password' => '', 
];  
$resolver = new OptionsResolver[]; 
$resolver->setDefaults[array[ 
   'host'     => '', 
   'username' => '', 
   'password' => '', 
]]; 
$resolved_options = $resolver->resolve[$options];

OptionsResolver component can be installed using the following command.

composer require symfony/options-resolver 

Dotenv

Dotenv component provides various options to parse .env files and the variable defined in them to be accessible via getenv[], $_ENV, or $_SERVER. Dotenv component can be installed using the following command.

composer require symfony/dotenv

Cache

Cache component provides an extended PSR-6 implementation. It can be used to add cache functionality to our web application. Since it follows PSR-6, it is easy to get started and it can be easily used in place of another PSR-6 based cache component. Cache component can be installed using the following command.

composer require symfony/cache 

Intl

Intl component is the replacement library for C Intl extension. Intl component can be installed using the following command.

composer require symfony/intl

Translation

Translation component provides various options to internationalize our application. Normally, the translation details of different languages will be stored in a file, one file per language, and it will be loaded dynamically during runtime of the application. There are different formats to write a translation file. Translation component provides various options to load any type of format, such as plain PHP file, CSV, ini, Json, Yaml, ICU Resource file, etc. Translation component can be installed using the following command.

composer require symfony/translation

Workflow

Workflow component provides advanced tools to process a finite state machine. By providing this functionality in a simple and object-oriented way, Workflow component enables advanced programming in PHP with relative ease. We will learn about it in detail in the Advanced Concept chapter.

Workflow component can be installed using the following command.

composer require symfony/workflow 

Yaml

Yaml component provides an option that parses the YAML file format and converts it into PHP arrays. It also able to write YAML file from plain php array. Yaml component can be installed using the following command.

composer require symfony/yaml

Ldap

Ldap component provides PHP classes to connect to a LDAP or Active directory server and authenticate the user against it. It provides an option to connect to a Windows domain controller. Ldap component can be installed using the following command.

composer require symfony/ldap

Debug

Debug component provides various options to enable debugging in PHP environment. Normally, debugging PHP code is hard but the debug component provides simple classes to ease the process of debugging and make it clean and structured. Debug component can be installed using the following command.

composer require symfony/debug

Stopwatch

Stopwatch component provides Stopwatch class to profile our PHP code. A simple usage is as follows.

use Symfony\Component\Stopwatch\Stopwatch; 
$stopwatch = new Stopwatch[]; 
$stopwatch->start['somename'];  

// our code to profile 
$profiled_data = $stopwatch->stop['somename'];  
echo $profiled_data->getPeriods[]

Stopwatch component can be installed using the following command.

composer require symfony/stopwatch

VarDumper

VarDumper component provides better dump[] function. Just include the VarDumper component and use the dump function to get the improved functionality. VarDumper component can be installed using the following command.

composer require symfony/var-dumper

BrowserKit

BrowserKit component provides an abstract browser client interface. It can be used to test web application programmatically. For example, it can request a form, enter the sample data and submit it to find any issue in the form programmatically. BrowserKit component can be installed using the following command.

composer require symfony/browser-kit

PHPUnit Bridge

PHPUnit Bridge component provides many options to improve the PHPUnit testing environment. PHPUnit Bridge component can be installed using the following command.

composer require symfony/phpunit-bridge

Asset

Asset component provides a generic asset handling in a web application. It generates URL for the assets such as CSS, HTML, JavaScript and also performs version maintenance. We will check the asset component in detail in View Engine chapter. Asset component can be installed using the following command.

composer require symfony/asset

CssSelector

CssSelector component provides an option to convert CSS based Selectors into XPath expression. A web developer knows the CSS based Selectors expression more than XPath expression, but the most efficient expression to find an element in HTML and XML document is XPath Expression.

CssSelector enables the developer to write the expression in CSS Selectors, however, the component converts it to XPath expression before executing it. Thus, the developer has an advantage of simplicity of CSS Selectors and efficiency of XPath expression.

CssSelector component can be installed using the following command.

composer require symfony/css-selector

DomCrawler

DomCrawler component provides various options to find the element in HTML and XML document using DOM concept. It also provides option to use XPath expression to find an element. DomCrawler component can be used along with CssSelector component to use CSS selectors instead of XPath expression. DomCrawler component can be installed using the following command.

composer require symfony/dom-crawler

Form

Form component enables easy creation of form in a web application. We will learn form programming in detail in Form chapter. Form component can be installed using the following command.

composer require symfony/form

HttpFoundation

HttpFoundation component provides an object-oriented layer to the HTTP specification. By default, PHP provides HTTP request and response details as array-based object such as $_GET, $_POST, $_FILES, $_SESSION, etc. HTTP based functionality such as setting a cookie can be done using simple, plain old function setCookie[]. HttpFoundation provides all HTTP related functionality in a small set of classes like Request, Response, RedirectResponse, etc., We will learn about these classes in the later chapters.

HttpFoundation component can be installed using the following command.

composer require symfony/http-foundation

HttpKernel

HttpKernel component is the core component in the Symfony web setup. It provides all the functionalities required for a web application - from receiving the Request object to sending back the Response object. The complete architecture of the Symfony web application is provided by HttpKernel as discussed in the architecture of a Symfony web framework.

HttpKernel component can be installed using the following command.

composer require symfony/http-kernel

Routing

Routing component maps the HTTP request to a pre-defined set of configuration variables. Routing decides which part of our application should handle a request. We will learn more about the routing in Routing chapter.

Routing component can be installed using the following command.

composer require symfony/filesystem

Templating

Templating component provides the necessary infrastructure to build an efficient template system. Symfony uses the Templating component for its View engine implementation. We will learn more about Templating component in View engine chapter.

Templating component can be installed using the following command.

composer require symfony/templating

Validator

Validator component provides an implementation of JSR-303 Bean Validation Specification. It can be used to validate a form in a web environment. We will learn more about Validator in Validation chapter.

Validator component can be installed using the following command.

composer require symfony/validator

Security

Security component provides complete security system for our web application, be it HTTP basic authentication, HTTP digest authentication, interactive form based authentication, X.509 certification login, etc. It also provides authorization mechanism based on the user role through in-built ACL system. We will learn more in detail in the Advanced Concept chapter.

Security component can be installed using the following command.

composer require symfony/security

Symfony - Service Container

In any application, objects tend to increase as the application grows. As objects increase, the dependency between the objects also increases. Object dependency needs to be handled properly for a successful application.

As discussed in the Components chapter, Symfony provides an easy and efficient component, DependencyInjection to handle object dependency. A service container is a container of objects with properly resolved dependency between them. Let us learn how to use DependencyInjection component in this chapter.

Let us create a Greeter class. The purpose of the Greeter class is to greet the user as shown in the following example.

$greeter = new Greeter['Hi']; 
$greeter->greet['Jon']; // print "Hi, Jon" 

The complete code of the Greeter class is as follows.

class Greeter { 
   private $greetingText; 
   
   public function __construct[$greetingText] { 
      $this->greetingText = $greetingText; 
   }  
   public function greet[$name] { 
      echo $this->greetingText . ", " . $name . "\r\n"; 
   } 
}

Now, let us add Greeter class to the service container. Symfony provides ContainerBuilder to create a new container. Once the container is created, Greeter class can be registered into it using the container's register method.

use Symfony\Component\DependencyInjection\ContainerBuilder; 
$container = new ContainerBuilder[]; 
$container 
   ->register['greeter', 'Greeter'] 
   ->addArgument['Hi'];

Here, we have used static argument to specify the greeting text, Hi. Symfony provides a dynamic setting of parameter as well. To use a dynamic parameter, we need to choose a name and specify it between % and the parameter can be set using container's setParameter method.

$container = new ContainerBuilder[]; 
$container 
   ->register['greeter', 'Greeter'] 
   ->addArgument['%greeter.text%'];  
$container->setParameter['greeter.text', 'Hi'];

We have registered a Greeter class with proper setting. Now, we can ask the container to provide a properly configured Greeter object using the container get method.

$greeter = $container->get['greeter']; 
$greeter->greet['Jon']; // prints "Hi, Jon" 

We have successfully registered a class, Greeter into container, fetched it from the container and used it. Now, let us create another class User, which use Greeter class and see how to register it.

class User { 
   private $greeter;  
   public $name; 
   public $age;  
   
   public function setGreeter[\Greeter $greeter] { 
      $this->greeter = $greeter; 
   }  
   public function greet[] { 
      $this->greeter->greet[$this->name]; 
   } 
}

The User class gets the Greeter class using one of its setter method, setGreeter. For this scenario, Symfony provides a method, addMethodCall and a class, Reference to refer another class as shown in the following code.

use Symfony\Component\DependencyInjection\Reference;  
$container 
   ->register['user', 'User'] 
   ->addMethodCall['setGreeter', array[new Reference['greeter']]]; 

Finally, we have registered two classes, Greeter and User having a strong relation between them. Now, we can safely fetch the User object with properly configured Greeter class from the container as shown in the following code.

$container->setParameter['greeter.text', 'Hi']; 
$user = $container->get['user']; 
$user->name = "Jon"; 
$user->age = 20; 
$user->greet[]; // Prints "Hi, Jon"

We have seen how to configure an object in a container using PHP itself. Symfony provides other mechanisms as well. They are XML and YAML configuration files. Let us see how to configure a container using YAML. For this, install symfony/config and symfony/yaml components along with symfony/dependency-injection components.

cd /path/to/dir 
mkdir dependency-injection-example 
cd dependency-injection-example 
composer require symfony/dependency-injection 
composer require symfony/config 
composer require symfony/yaml

YAML configuration will be written in a separate file, services.yml. YAML configuration consists of two sections, parameters and services. Parameters section defines all required parameters. Services section defines all objects. Services section is further divided into multiple sections namely, class, arguments, and calls. Class specifies the actual class. Arguments specifies the constructor's arguments. Finally, calls specify the setter methods. Another class can be referred using @ symbol, @greeter.

parameters: 
   greeter.text: 'Hello' 
services: 
   greeter: 
      class: Greeter
      arguments: ['%greeter.text%'] 
   user: 
      class: User 
      calls: 
         - [setGreeter, ['@greeter']] 

Now, services.yml can be loaded and configured using FileLoader and YamlFileLoader as shown in the following code.

use Symfony\Component\Config\FileLocator; 
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;  

$yamlContainer = new ContainerBuilder[]; 
$loader = new YamlFileLoader[$yamlContainer, new FileLocator[__DIR__]]; 
$loader->load['services.yml'];  

$yamlUser = $yamlContainer->get['user']; 
$yamlUser->name = "Jon"; 
$yamlUser->age = 25; 
$yamlUser->greet[]; 

The complete code listing is as follows.

main.php

services.yml

parameters: 
   greeter.text: 'Hello' 
services: 
   greeter: 
      class: Greeter 
      arguments: ['%greeter.text%'] 
   user: 
      class: User 
      calls: 
         - [setGreeter, ['@greeter']] 

Symfony web framework uses the dependency injection component extensively. All the components are bound by the centralized service container. Symfony web framework exposes the container in all its Controller through container property. We can get all object registered in it, say logger, mailer, etc., through it.

$logger = $this->container->get['logger']; 
$logger->info['Hi']; 

To find the object registered in the container, use the following command.

cd /path/to/app 
php bin/console debug:container

There are around 200+ objects in the hello web app created in the installation chapter.

Symfony - Events and EventListener

Symfony provides event-based programming through its EventDispatcher component. Any enterprise application needs event-based programming to create a highly customizable application. Events is one of the main tools for the objects to interact with each other. Without events, an object does not interact efficiently.

The process of event based programming can be summarized as - An object, called Event source asks the central dispatcher object to register an event, say user.registered. One or more objects, called listener asks the central dispatcher object that it wants to listen to a specific event, say user.registered. At some point of time, the Event source object asks the central dispatcher object to dispatch the event, say user.registered along with an Event object with the necessary information. The central dispatcher informs all listener objects about the event, say user.registered and its Event* object.

In event-based programming, we have four types of objects: Event Source, Event Listener, Even Dispatcher, and the Event itself.

Let us write a simple application to understand the concept.

Step 1 − Create a project, event-dispatcher-example.

cd /path/to/dir 
mkdir event-dispatcher-example 
cd event-dispatcher-example 
composer require symfony/event-dispatcher 

Step 2 − Create a class, .User.

class User { 
   public $name; 
   public $age; 
}  

$user = new User[]; 
$user->name = "Jon"; 
$user->age = 25

Step 3 − Create an event, UserRegisteredEvent.

use Symfony\Component\EventDispatcher\Event;  
class UserRegisteredEvent extends Event {
   const NAME = 'user.registered';  
   protected $user;  
   
   public function __construct[User $user] { 
      $this-name . "\r\n"; 
         echo $user->age . "\r\n"; 
   } 
}  
$listener = new UserListener[]; 

Step 5 − Create an event dispatcher object.

use Symfony\Component\EventDispatcher\EventDispatcher;  
$dispatcher = new EventDispatcher[]; 

Step 6 − Connect listener and event using dispatcher object and its method, addListener.

$dispatcher 
   ->addListener[ 
      UserRegisteredEvent::NAME,  
      array[$listener, 'onUserRegistrationAction']];  

We can also add an anonymous function as event listener as shown in the following code.

$dispatcher 
   ->addListener[ 
      UserRegisteredEvent::NAME,  
      
      function[Event $event] { 
         $user = $event->getUser[]; 
         echo $user->name . "\r\n"; 
      }]; 

Step 7 − Finally, fire / dispatch the event using event dispatcher's method, dispatch.

 $dispatcher->dispatch[UserRegisteredEvent::NAME, $event];

The complete code listing is as follows.

main.php

Result

Jon 
Jon 
25

Symfony web framework has a lot of events and one can register listener for those events and program it accordingly. One of the sample event is kernel.exception and the corresponding event is GetResponseForExceptionEvent, which holds the response object [the output of a web request]. This is used to catch the exception and modify the response with generic error information instead of showing runtime error to the users.

Symfony - Expression

As we discussed earlier, expression language is one of the salient features of Symfony application. Symfony expression is mainly created to be used in a configuration environment. It enables a non-programmer to configure the web application with little effort. Let us create a simple application to test an expression.

Step 1 − Create a project, expression-language-example.

cd /path/to/dir 
mkdir expression-language-example 
cd expression-language-example 
composer require symfony/expression-language 

Step 2 − Create an expression object.

use Symfony\Component\ExpressionLanguage\ExpressionLanguage; 
$language = new ExpressionLanguage[];

Step 3 − Test a simple expression.

echo "Evaluated Value: " . $language->evaluate['10 + 12'] . "\r\n" ; 
echo "Compiled Code: " . $language->compile['130 % 34'] . "\r\n" ;

Step 4 − Symfony expression is powerful such that it can intercept a PHP object and its property as well in the expression language.

class Product { 
   public $name; 
   public $price; 
} 
$product = new Product[]; 
$product->name = 'Cake'; 
$product->price = 10;  

echo "Product price is " . $language 
   ->evaluate['product.price', array['product' => $product,]] . "\r\n";  
echo "Is Product price higher than 5: " . $language 
   ->evaluate['product.price > 5', array['product' => $product,]] . "\r\n"; 

Here, the expression product.price and product.price > 5 intercept $product object's property price and evaluate the result.

The complete coding is as follows.

main.php

 

Result

Evaluated Value: 22 
Compiled Code: [130 % 34] 
Product price is 10 
Is Product price higher than 5: 1

Symfony - Bundles

A Symfony bundle is a collection of files and folders organized in a specific structure. The bundles are modeled in such a way that it can be reused in multiple applications. The main application itself is packaged as a bundle and it is generally called AppBundle.

A bundle may be packaged specific to an application such as AdminBundle [admin section], BlogBundle [site's blog], etc. Such bundles cannot be shared between an application. Instead, we can model a certain part of the application such as blogs as generic bundle so that we can simply copy the bundle from one application to another application to reuse the blog functionality.

Structure of a Bundle

The basic structure of a bundle is as follows.

  • Controller − All controller need to be placed here.

  • DependencyInjection − All dependency injection related code and configuration need to be placed here.

  • Resources/config − Bundle related configurations are placed here.

  • Resources/view − Bundle related view templates are placed here.

  • Resources/public − Bundle related stylesheets, JavaScripts, images, etc., are placed here.

  • Tests − Bundle related unit test files are placed here.

Creating a Bundle

Let us create a simple bundle, TutorialspointDemoBundle in our HelloWorld application.

Step 1 − Choose a namespace. Namespace of a bundle should include vendor name and bundle name. In our case, it is Tutorialspoint\DemoBundle.

Step 2 − Create an empty class, TutorialspointDemoBundle by extending Bundle class and place it under src/Tutorialspoint/DemoBundle.

namespace Tutorialspoint\DemoBundle; 
use Symfony\Component\HttpKernel\Bundle\Bundle;  

class TutorialspointDemoBundle extends Bundle { 
}

Step 3 − Register the class in the list of bundle supported by the application in AppKernel class.

public function registerBundles[] { 
   $bundles = array[ 
      // ... 
      // register your bundle 
      new Tutorialspoint\DemoBundle\TutorialspointDemoBundle[], 
   ]; 
   return $bundles; 
}

This is all is needed to create an empty bundle and all other concepts are the same as that of the application. Symfony also provides a console command generate:bundle to simplify the process of creating a new bundle, which is as follows.

php bin/console generate:bundle --namespace = Tutorialspoint/DemoBundle

Result

Welcome to the Symfony bundle generator!

Are you planning on sharing this bundle across multiple applications? [no]: no  

Your application code must be written in bundles. This command helps 
you generate them easily.  

Give your bundle a descriptive name, like BlogBundle. 
Bundle name [Tutorialspoint/DemoBundle]:   

In your code, a bundle is often referenced by its name. It can be the 
concatenation of all namespace parts but it's really up to you to come 
up with a unique name [a good practice is to start with the vendor name]. 
Based on the namespace, we suggest TutorialspointDemoBundle.  

Bundle name [TutorialspointDemoBundle]:  
Bundles are usually generated into the src/ directory. Unless you're 
doing something custom, hit enter to keep this default!
Target Directory [src/]:   

What format do you want to use for your generated configuration?  

Configuration format [annotation, yml, xml, php] [annotation]:

Bundle generation

> Generating a sample bundle skeleton into app/../src/Tutorialspoint/DemoBundle 
   created ./app/../src/Tutorialspoint/DemoBundle/ 
   created ./app/../src/Tutorialspoint/DemoBundle/TutorialspointDemoBundle.php 
   created ./app/../src/Tutorialspoint/DemoBundle/Controller/ 
   created ./app/../src/Tutorialspoint/DemoBundle/Controller/DefaultController.php 
   created ./app/../tests/TutorialspointDemoBundle/Controller/   
   created ./app/../tests/TutorialspointDemoBundle/Controller/DefaultControllerTest.php 
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/views/Default/   
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/views/Default/index.html.twig 
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/config/ 
   created ./app/../src/Tutorialspoint/DemoBundle/Resources/config/services.yml 
> Checking that the bundle is autoloaded 
> Enabling the bundle inside app/AppKernel.php 
   updated ./app/AppKernel.php 
> Importing the bundle's routes from the app/config/routing.yml file 
   updated ./app/config/routing.yml 
> Importing the bundle's services.yml from the app/config/config.yml file 
   updated ./app/config/config.yml 
Everything is OK! Now get to work :].  

Creating a Simple Web Application

This chapter explains how to create a simple application in Symfony framework. As discussed earlier, you know how to create a new project in Symfony.

We can take an example of “student” details. Let’s start by creating a project named “student” using the following command.

symfony new student

After executing the command, an empty project is created.

Controller

Symfony is based on the Model-View-Controller [MVC] development pattern. MVC is a software approach that separates application logic from presentation. Controller plays an important role in the Symfony Framework. All the webpages in an application need to be handled by a controller.

DefaultController class is located at “src/AppBundle/Controller”. You can create your own Controller class there.

Move to the location “src/AppBundle/Controller” and create a new StudentController class.

Following is the basic syntax for StudentController class.

StudentController.php

namespace AppBundle\Controller; 
use Symfony\Component\HttpFoundation\Response;  
class StudentController { 
} 

Now, you have created a StudentController. In the next chapter, we will discuss more about the Controller in detail.

Create a Route

Once the Controller has been created, we need to route for a specific page. Routing maps request URI to a specific controller's method.

Following is the basic syntax for routing.

namespace AppBundle\Controller;  
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;  

class StudentController { 
   /** 
      * @Route["/student/home"] 
   */ 
   public function homeAction[] { 
      return new Response['Student details application!']; 
   } 
}

In the above syntax, @Route[“/student/home”] is the route. It defines the URL pattern for the page.

homeAction[] is the action method, where you can build the page and return a Response object.

We will cover routing in detail in the upcoming chapter. Now, request the url “//localhost:8000/student/home” and it produces the following result.

Result

Symfony - Controllers

Controller is responsible for handling each request that comes into Symfony application. Controller reads an information from the request. Then, creates and returns a response object to the client.

According to Symfony, DefaultController class is located at “src/AppBundle/Controller”. It is defined as follows.

DefaultController.php

Bài Viết Liên Quan

Chủ Đề