Symfony Framework - A Complete Beginner's Guide

Posted in Symfony
Symfony Framework

Symfony is an open-source PHP framework designed for web applications. This article will discuss how Symfony came into existence, important components, architecture, workflow, basic steps for installation, and more.

It has established itself as a foundation for web services. Symfony contains reusable PHP libraries and components. Projects like Laravel and Drupal use Symfony components in their applications.

Symfony was developed to reduce creation and maintenance time for web applications and avoid repetitive tasks. It is greatly influenced and inspired by the Spring framework. 

History of Symfony

Symfony was released by SensioLabs and published on October 18, 2005, as free software. It was released under the MIT license. However, a more stable first version was released in 2007, yet, it wasn’t as promising as version 2.0. However, developers were finding major issues with the upgrade and backward compatibility. The best and most promising version was 2.3, which had good stability and features. The upgrades after that, 2.4, 2.5, 2.6, were not so prominent, and all the further releases were backward compatible. The current version is 5.2, which has some significant features like Pseudo-localization, 24-bit colors on the console, TranslatableMessage objects, support for PHP 8 attributes/annotations, and more.

Features

As we mentioned before, the main aim of Symfony is to optimize web applications. Symfony frameworks have the following unique features:

  • MVC based micro-framework (Model-View-Controller)
  • Highly performant PHP framework
  • Reusable components that are decoupled
  • Error logging and session management features
  • Flexible URI routing
  • Vibrant, active community
  • Highly mature Twig template engine 
  • Extensible, good code readability
  • Support for multiple database platforms

Symfony Architecture

The architecture is simple and consists of components and bundles that are reusable. 

Components provide single specialized functionality. For example, the HTTP component, cache component, filesystem component, etc. These are nothing but standalone PHP libraries. 

Bundles are like plugins and are easier to create and use. A bundle can use many Symfony components and provide many features. A Symfony core web-framework itself is a bundle (FrameworkBundle). 

Components can access any number of bundles. The common bundles used in the framework are FrameworkBundle, FrameworkExtraBundle, DoctrineBundle. Other than that, we can have custom bundles and doctrine bundles. 

The Symfony application can access components and bundles independently. The below diagram represents the complete relationship between components and bundles:

Symphony Framework Part 2

Other than FrameworkBundle, the following components need some mention as below:

HttpKernel

This component provides the building blocks required to create fast and flexible HTTP-based applications. It can be installed using the command:

$ composer require symfony/HTTP-kernel

(Don’t worry if you don’t understand the above right now, we will cover what this is in the next section!)

Some projects that used the HttpKernel component are Drupal, OroCRM, Lumen, Thelia, Sulu, etc. The kernel internally defines a workflow that starts with a request and ends in a response. It resolves the controller, arguments and gets the response using the handle() method. Events drive all the steps in the HttpKernel workflow.

HttpFoundation

The HttpFoundation component is responsible for adding the object-oriented layer to the HTTP specification. The global variables that are part of every HTTP request, like, GET, POST, COOKIE, SESSION, etc., are wrapped in an object-oriented layer. To install this component, give the command as:

$ composer require symfony/HTTP-foundation

DoctrineBundle

To know about DoctrineBundle, we need to know what Doctrine is.

Doctrine is a project or set of PHP libraries that provide persistent services. It contains ORM (Object-Relational Mapper) and database abstraction layer (DBAL). It uses the Doctrine Query Language (DQL), the object-oriented counterpart of SQL, to write database queries. With Doctrine, there is no need to store and maintain complex XML database schemas. 

The DoctrineBundle integrates the ORM and DBAL layers into Symfony applications. You also get a set of console commands, configuration options, and web debug toolbar collector. To install the bundle, type:

$ composer require doctrine/doctrine-bundle

To get a database-specific bundle, for example, if you want DoctrineMongoDBBundle, you should add the specific bundle to the composer.json file:

"require": {
       "doctrine/mongodb-odm-bundle": "^3.0"
    },

and then install the dependencies using the update command from the compose.json file’s directory (location):

$ php composer.phar update doctrine/mongodb-odm-bundle

How to Download and Install Symfony

To install Symfony on your machine, you should have PHP 5.4 or later. Apart from this, it is good to have a web-server like WAMP or Microsoft IIS for Windows, MAMP for Mac, LAMP for Linux, or XAMP/Nginx (Multi-platform). 

You can directly install the installer through command-line using the following commands:

$mkdir -p /usr/local/bin 

$curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony 

$chmod a+x /usr/local/bin/symphony

Once we have installed the installer, we can create a new application:

symfony new <our_app_name>

 

Upon execution of this command, Symfony will be downloaded on your system, and the project will be created with its directory ‘first app/.’ 

To run the app, we need to start the server:

cd <our_app_name> 

PHP bin/console server:run

To see if the installation is successful, open the browser and go to localhost:8080. You should see a welcome message:

Welcome message

Once the framework is installed, you can install the required components and bundles, as shown in the previous section!

Simple Symfony Workflow

The Symfony framework provides all the features required by an enterprise application. Here is a typical workflow of how a Symfony web application works:

Symphony Frameworks Part 1

A typical workflow consists of the following steps:

  • The user makes an application request via the browser, using the HTTP protocol, i.e., http://xyz.com
  • In turn, the browser passes the request to a web server like Apache, WebSphere, etc.
  • The server then forwards the user request to the underlying PHP layer. The PHP layer, in turn, redirects it to the Symfony web framework. 
  • The core component HttpKernel resolves the controller (we saw this in the architecture) of the request. It uses the routing component to forward the request to the target request controller.
  • The main business logic is executed in the controller layer.
  • Next, the DoctrineORM comes into the picture, through which the controller interacts with the Model. The DoctrineORM is responsible for connecting to the data source.
  • Once the process is complete, the controller generates a response on its own or creates it through the View engine. View engine is nothing but a component responsible for converting the response into an HTML format.
  • The response is sent back to the webserver. The web server then transfers the response to the user (browser).

Symfony Framework Advantages

Advantages of Symfony are:

  1. Fast-Paced Development: Since Symfony is a component-based framework, it can be easily installed and used. This makes development faster and efficient and helps developers build applications quickly.
  2. Flexibility: With features like dependency Injection (DI) and event dispatching, Symfony makes it easy for developers to create even complex applications with the highest level of configuration, giving flexibility to the code.
  3. Extensibility: Since everything is a bundle and adds unique functionality, developers can reuse bundles or add to the framework. There is no need to modify the framework; just the bundle can be configured to suit specific project requirements.
  4. Stability: After the initial glitches, the new versions of Symfony have been quite stable and sustainable. They are also compatible with public APIs. 
  5. Ease of Development: Developers do not need to worry about minor functionalities and focus on their business logic while the framework takes care of the core functionalities. Symfony works for small to big projects because of its component and bundle-based architecture. Web debugging toolbars help address different issues in the early stage of development, ensuring high-quality deliverables.

Symfony Components

Symfony is easy to learn because it consists of components and bundles, and if you know about the core components and bundles, you can easily create new applications. Some important components are:

1. Finder

It provides classes to search files and directories in the mentioned path quickly by iterating over the files.

2. Filesystem

Provides commands to perform basic file operations like creating a file or a folder, checking if a file exists, etc.

3. ClassLoader

Provides the implementation for class loader standards of PSR-0 and PSR-4. It also does auto loading of classes. 

4. DependencyInjection

Provides containers to handle dependencies. The framework uses this component extensively using the service container.

5. EventDispatcher

Provides event-based PHP programming. Objects can communicate with each other by dispatching and listening to events.  

6. Serializer

Through Serializer, we can convert PHP objects into different formats like JSON, binary, XML, etc., and convert them back to PHP objects without any loss of data.

7. ExpressionLanguage

Provides an expression engine that makes code neater and smaller. ExpressionLanguage consists of two ways for working with expressions: evaluation (the expression is evaluated without compilation to PHP) and compilation (the expression is compiled so that it can be cached and then evaluated). It supports many syntaxes like literals, objects, operators, functions, arrays, etc.

8. Workflow

Allows for advanced PHP programming by giving advanced tools for processing finite state machines. 

9. HttpFoundation

Provides an object-oriented layer to the HTTP request and response objects supplied by default by PHP.

10. Form

Enables easy form creation in a web application

11. HttpKernel

Takes care of the entire request-response process of a web application. It is the main component of Symfony architecture. 

12. Routing

Routing determines the part of the application that should handle a particular request. It maps the request in hand to a set of pre-defined configuration variables.

There are many more components of Symfony, and you can visit the official Symfony website to check them all.

Symfony Bundle

A bundle is a collection of files and folders arranged in a particular structure. The arrangement is made such that multiple applications can reuse the bundles. The main Symfony application is packaged as a bundle and is called the AppBundle. Some other examples of a bundle can be AdminBundle (an admin site), HelloMobileBundle (a hello mobile app), etc.

The bundle consists of the following:

  • Controller: All the controllers are placed in the controller folder
  • Dependency Injection: All the files related to DI and configuration go here
  • Resources/config: for bundle related configurations
  • Resources/public: CSS, JS, images, etc., related to the bundle go here.
  • Resources/view: to store all the view templates related to the bundle
  • Tests: All the bundle unit tests are stored in this folder

You can easily customize a part of any third-party bundle that you want to use for your application. Check the Symfony bundle overriding for more details. 

Further Reading

We have covered enough for you to get started with Symfony. The article should have generated good interest in Symfony, and you would be able to follow the Symfony framework's basic concepts. To learn Symfony, you should know the PHP framework. To learn Symfony, check out our comprehensive list of courses and tutorials (some of them are completely free!!). You can also read some top books like A year with Symfony or The definitive guide to Symfony.

Leave a comment

Your email will not be published
Cancel