Symfony - Components


Advertisements

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/<component_name> 

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.

<?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; 
   } 
?>  

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.

<?php 
   require __DIR__ . '/vendor/autoload.php'; 
   use Symfony\Component\Console\Application; 
   
   $app = new Application(); 
   $app->run(); 
?> 

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.

<?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;  
   
   class HelloCommand extends Command { 
      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'); 
      }  
      protected function execute(InputInterface $input, OutputInterface $output) { 
         $name = $input->getArgument('name'); 
         $output->writeln('Hello, ' . $name);
      }  
      $app = new Application(); 
      $app->add(new HelloCommand()); 
      $app->run(); 
   }         
?>      

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'     => '<db_host>', 
   'username' => '<db_user>', 
   'password' => '<db_password>', 
);  
$resolver = new OptionsResolver(); 
$resolver->setDefaults(array( 
   'host'     => '<default_db_host>', 
   'username' => '<default_db_user>', 
   'password' => '<default_db_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
Advertisements