- Complete Working Example
- Symfony - CMF Edition
- Symfony - REST Edition
- Symfony - Advanced Concepts
- Symfony - Unit Testing
- Symfony - Email Management
- Symfony - Logging
- Symfony - Internationalization
- Cookies & Session Management
- Symfony - Ajax Control
- Symfony - File Uploading
- Symfony - Validation
- Symfony - Forms
- Symfony - Doctrine ORM
- Symfony - View Engine
- Symfony - Routing
- Symfony - Controllers
- Creating a Simple Web Application
- Symfony - Bundles
- Symfony - Expression
- Symfony - Events & EventListener
- Symfony - Service Container
- Symfony - Components
- Symfony - Architecture
- Symfony - Installation
- Symfony - Introduction
- Symfony - Home
Symfony Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Symfony - Components
As discussed earper, Symfony components are standalone PHP pbrary providing a specific feature, which can be used in any PHP apppcation. Useful new components are being introduced in each and every release of Symfony. Currently, there are 30+ high quapty components in Symfony framework. Let us learn about the usage of Symfony components in this chapter.
Instalpng 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 apppcation and try to install Filesystem component.
Step 1 − Create a folder for the apppcation, 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 SymfonyComponentFilesystemFilesystem; use SymfonyComponentFilesystemExceptionIOExceptionInterface; $fs = new Filesystem(); try { $fs->mkdir( ./sample-dir ); $fs->touch( ./sample-dir/text.txt ); } catch (IOExceptionInterface $e) { echo $e; } ?>
The first pne is very important, which loads all the necessary classes from all the components installed using the Composer command. The next pnes use the Filesystem class.
Step 4 − Run the apppcation 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 functionapties such as creating a new apppcation, 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 apppcation 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 SymfonyComponentConsoleApppcation; $app = new Apppcation(); $app->run(); ?>
Apppcation class sets up the necessary functionapty of a bare-bone console apppcation.
Step 3 − Run the apppcation, 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 apppcation 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 pst Lists commands
Step 4 − Create a class called HelloCommand extending Command class in the main.php itself.
use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputInterface; use SymfonyComponentConsoleOutputOutputInterface; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { }
The apppcation 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 apppcation using the add method of Apppcation class.
$app->add(new HelloCommand());
The complete apppcation is as follows.
<?php require __DIR__ . /vendor/autoload.php ; use SymfonyComponentConsoleApppcation; use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputInterface; use SymfonyComponentConsoleOutputOutputInterface; use SymfonyComponentConsoleInputInputArgument; 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 Apppcation(); $app->add(new HelloCommand()); $app->run(); } ?>
Step 10 − Now, execute the apppcation 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 apppcation, which can be used to invoke the commands in an apppcation.
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 functionapty.
class Product { private $name = Cake ; private $price = 10; pubpc function getName() { return $this->name; } pubpc 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 pstening to them. We will learn how to create event and psten 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
Seriapzer
Seriapzer 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.
Seriapzer component can be installed using the following command.
composer require symfony/seriapzer
Config
Config component provides options to load, parse, read, and vapdate 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 apppcation 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-pner 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 vapdate 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 vapdate the entries before using it to connect to a database. OptionsResolver simppfies this task by providing a simple class OptionsResolver and a method resolver, which resolves the database setting and if there is any vapdation 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 functionapty to our web apppcation. 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 pbrary for C Intl extension. Intl component can be installed using the following command.
composer require symfony/intl
Translation
Translation component provides various options to internationapze our apppcation. 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 apppcation. 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 functionapty 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 SymfonyComponentStopwatchStopwatch; $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 functionapty. VarDumper component can be installed using the following command.
composer require symfony/var-dumper
BrowserKit
BrowserKit component provides an abstract browser cpent interface. It can be used to test web apppcation 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 handpng in a web apppcation. 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 simppcity 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 apppcation. 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 functionapty such as setting a cookie can be done using simple, plain old function setCookie(). HttpFoundation provides all HTTP related functionapty in a small set of classes pke 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 functionapties required for a web apppcation - from receiving the Request object to sending back the Response object. The complete architecture of the Symfony web apppcation 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 apppcation 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
Vapdator
Vapdator component provides an implementation of JSR-303 Bean Vapdation Specification. It can be used to vapdate a form in a web environment. We will learn more about Vapdator in Vapdation chapter.
Vapdator component can be installed using the following command.
composer require symfony/vapdator
Security
Security component provides complete security system for our web apppcation, 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/securityAdvertisements