Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why Symphony as your PHP Framework 
3.
Symfony Framework Features 
4.
Symfony architecture 
4.1.
Symfony Framework Components
4.2.
Symfony Framework Bundle 
5.
Symfony CLI 
6.
Setting Up Symfony Framework Project 
7.
Symfony project structure 
8.
Installing Symfony project dependencies 
9.
Symfony Creating Controller
10.
Symfony with twig template 
11.
Examples of Symfony Framework 
11.1.
1. Spotify 
11.2.
2. Dailymotion 
11.3.
3. Trivago 
11.4.
4. Drupal Console 
12.
Frequently asked questions 
12.1.
In the MVC model, which depicts the organization of our corporate entities? 
12.2.
How can console components be installed? 
12.3.
Which component offers different ways to read and write information about objects and arrays using string notation?
12.4.
What component offers a range of options for parsing.env files?
12.5.
Any URI typically has?
13.
Conclusion
Last Updated: Mar 27, 2024
Medium

What is PHP Framework Symfony?

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Symfony is a PHP framework for web projects and a collection of reusable PHP components. In 2005, Symfony was released as open-source software. Fabien Potencier is considered Symfony's original author. The Spring Framework served as a significant inspiration for Symfony.

Introduction image

 

Symfony uses numerous PHP open-source projects, including the Twig template engine, Doctrine object-relational mapping library, PDO database abstraction layer, PHPUnit test framework, and Swift Mailer email library.
 

Symfony Framework has developed its components, such as the Symfony YAML parser and Symfony Dependency Injector, development projects. The first to gain traction was CodeIgniter. Simple, attractive, and user-friendly web apps can be created with the aid of CodeIgniter.

Recommended Topic, Interpolation in Angular

Why Symphony as your PHP Framework 

Why symphony as your php framework

There are numerous benefits to using Symfony Framework as your preferred PHP framework, including: 

  • Only the essential components required to bootstrap the framework and manage the HTTP lifecycle are installed when starting a new Symfony Project, making it incredibly lightweight and perfect for Microservices or APIs. Then, you can add more components as you need to create more complex applications. 
     
  • With the help of its component system, it is incredibly modular.
     
  • Written code that adheres to OOP Design Patterns and industry standards like Dependency Injection.
     
  • PSR-2 (code styling), PSR-3 (logger interface), PSR-4 (autoloader), PSR-6 (caching interface), and PSR-11 (service container) are just a few of the PHP-FIG standards that are implemented, allowing for simple interoperability with other libraries.
     
  • Not bound to a particular ORM, templating engine, database system, etc.
     
  • Wonderful documentation
     
  • Continuous improvement of performance and development experience.
     
  • We are using the most recent PHP features while being mature and stable.
     
  • It is ideal for enterprise or more complicated projects due to its well-defined release process, long-term support, and great compromise with Backwards compatibility.
     
  • According to PHP Benchmarks, it is by far the fastest PHP framework.
     
  • On top of Symfony, many excellent platforms that support Rapid Application Development, such as API Platform, have been established.

Must Read PHP Projects With Source Code

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Symfony Framework Features 

Features

With each release, Symfony gains new features aimed at streamlining the creation of web applications.

The following are some of the critical characteristics of the Symfony Framework: 

  • 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 vast and active community
     
  • Standardization and interoperability of applications
     
  • Security against cross-site request forgery and other attacks
     
  • Twig template engine
     

Developers have a lot of flexibility with Symfony. It has excellent debugging, code readability, and program development features. Symfony is a full-stack web framework that makes building web applications very easy. Clients can obtain Symfony services from a variety of businesses.

The following are some advantages of using the Symfony Framework.

  • Symfony's microframework can be used to create a particular functionality. The entire framework can be installed or redeveloped.
     
  • It reduces the overhead of development time.
     
  • It is a highly sophisticated templating engine that provides users with content quickly.
     
  • All framework classes are compatible and easily extendable by programmers.

Symfony architecture 

Components from the Symfony framework are independent PHP libraries that give any PHP application special functionality. There are currently more than 30 high-quality components in the Symfony framework. Let's examine the applications of Symfony components: 

Symfony Architecture

Symfony Framework Components

  • Finder: Based on a number of criteria, the Finder component finds files and directories using an intuitive fluent interface. There are numerous ways to define search criteria in the component. They can all be chained together because they all implement a fluent interface.
     
  • Filesystem: The Filesystem component provides a platform-independent utility for file system operations and manipulating file/directory paths. The necessary filesystem utilities are included.
     
  • ClassLoader: This component automatically loads your project classes if they follow the accepted PHP conventions—use Composer class loading instead of this component, which has been deemed obsolete since Symfony 3.3.
     
  • DependencyInjection: By implementing a PSR-11 compatible service container, the DependencyInjection component enables you to benchmark and centralize how components are built into your application.
     
  • EventDispatcher: The EventDispatcher component provides tools for your application components to communicate with one another by dispatching and listening to events. To make all of this possible and your projects genuinely extensible, the Symfony EventDispatcher component implements the Mediator and Observer design patterns.
     
  • Serializer: The Serializer component transforms objects from one format (such as XML, JSON, or YAML) into another. 
     
  • ExpressionLanguage: A one-line program that returns a value, the ExpressionLanguage component has an engine for compiling and evaluating expressions.
     
  • Workflow: You can define a process or a life cycle for your object in an object-oriented manner using the workflow component. You also represent transitions, which describe the action taken to move from one place to another. Each step is referred to as a place.
     
  • HttpFoundation: The object-oriented layer of the HTTP specification is defined by the HttpFoundation component. The Symfony HttpFoundation component replaces the standard PHP global variables and functions with an object-oriented layer.
     
  • Form: The Form component allows for creating, processing, and reusing forms. You can solve the problem of enabling end users to interact with and modify data in your application with the help of the Form component.
     
  • HttpKernel: The HttpKernel component offers a structured method for converting a Request into a Response using the EventDispatcher component. It is adaptable enough to create a sophisticated CMS system, a micro-framework (Silex), or a full-stack framework (Symfony).
     
  • Routing: Your application launches a controller action to create a response when it receives a request. Every incoming URL is given a specific action to be taken, and the routing configuration allows for creating SEO-friendly URLs.

Symfony Framework Bundle 

A collection of carefully arranged files and folders is a Symfony bundle. The main application is packaged as a bundle, also known as an AppBundle, and the bundles are made to be reused across various applications.

An application-specific bundle can be packaged, such as AdminBundle (the admin section) or BlogBundle (the site's blog). Such bundles are not transferable between applications. To reuse the blog functionality in different applications, we can model a specific component of the application, like blogs, as a generic bundle.

  • Controller: Place all the controllers here.
     
  • DependencyInjection: Code and configuration for dependency injection must be placed here.
     
  • Resources/config: Configurations pertaining to bundles are located here. 
     
  • Resources/view: View templates related to bundles are found here.
     
  • Resources/public: Stylesheets, JavaScripts, images, and other file types related to bundles are put here.
     
  • Tests: Here is the unit test files related to bundles.

Symfony CLI 

A tool for developing and managing Symfony applications both locally and in the Symfony cloud is called Symfony CLI. It comes with a potent local web server for creating applications. The Symfony CLI is downloaded from https://symfony.com/download

Setting Up Symfony Framework Project 

PHP 7.2.5 or higher (and related libraries like php-xml or php-mcrypt) and composer are required to build a Symfony 5 project. Dependencies for the project are listed in the composer.json file. 

$ symfony new symfirst


PHP 7.2.5 or higher (and related libraries like PHP-XML or PHP-mcrypt) and Composer are required to build a Symfony 5 project. Dependencies for the project are listed in the composer.json file. 

$ cd symfirst


We build a new Symfony skeleton project using the Symfony tool. Similar to a micro framework, Symfony Skeleton requires that we install each module individually. Which modules we install is up to us. This is beneficial for education.

Symfony project structure 

The composer created a structure for a Symfony application.

$ ls -1ap --group-directories-first
./
../
bin/
config/
public/
src/
var/
vendor/
.env
.gitignore
composer.json
composer.lock
symfony.lock


The console tool, a command-line tool to execute different kinds of commands, is located in the bin directory. The web files are in the public directory. One file, index.php, a Symfony front controller, makes up a Symfony skeleton application.

Dependencies on external parties are kept in the vendor directory. Config files are located in the config directory. The src directory contains the source code. Temporary files, such as caching data, are found in the var directory.

Additionally, there are two particular hidden files:.env and.gitignore. Environment variables are created from the data in the.env file. Different tools, like ORM libraries, use environment variables. The.env should not be committed to the repositories because it might contain sensitive or machine-specific data. The.gitignore file instructs the git tool to ignore files that have been purposefully left untracked.

Dependencies for Composer are specified in composer.json. For later reinstallation, the Composer.lock keeps track of the precise versions installed. It guarantees that everyone working on a project has access to the same libraries. The appropriate lock file for Symfony recipes is Symfony.lock.

Installing Symfony project dependencies 

A few project dependencies will then be installed. 

$ composer require maker --dev


We install the maker component to create commands, controllers, form classes, or event subscribers.

$ composer require annotations twig


Two more Symfony modules are set up. You can configure your controllers using annotations by using the annotations feature. The twig enables Symfony applications to use the Twig template engine. 

Symfony Creating Controller

A PHP function called a Symfony controller creates and returns a Response object after reading data from the Request object. A file download, redirect, 404 error, HTML page, JSON, XML, or other response types are all possible.

$ php bin/console make:controller HelloController


A HelloController is made using the console tool. The controller is created in the directory src/Controller/. 

<?php


namespace App\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


class HelloController extends AbstractController
{
    /**
     * @Route("/plain", name="plain")
     */
    public function helloPlain(): Response
    {
        return new Response("Hello Coding Ninjas", Response::HTTP_OK,
            ['content-type' => 'text/plain']);
    }
}


The HelloController is shown here. The file src/Controller/HelloController.php contains it.

/**
 * @Route("/plain", name="plain")
 */
public function helloPlain() 
{


A route is a diagram connecting a controller method with a URL path. The helloPlain() function is linked to the /plain URL path by the @Route annotation.

return new Response("Hello Coding Ninjas",  Response::HTTP_OK,
  ['content-type' => 'text/plain']);

 

A Response object is the function's output. All the data required to be returned to the client in response to a specific request is contained in a Response object. The response content, the status code, and an array of HTTP headers are the three possible arguments that the function Object() { [native code] } can accept. Response::HTTP OK is the default status code, and text/HTML is the default content type.

 

$ symfony serve


Using symfony serve, we launch a local web development server.

$ curl 127.0.0.1:8000/plain


A GET request is sent to the plain route, and the text response is displayed. 

Symfony with twig template 

The project directory received a Twig template engine after using the Composer require twig command. A templates directory was also established. Our template files are placed in that directory. The extension of the template files is HTML.twig. 

<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;


class HelloController extends AbstractController
{
    /**
     * @Route("/plain", name="plain")
     */
    public function helloPlain(): Response
    {
        return new Response("Hello Coding Ninjas", Response::HTTP_OK,
            ['content-type' => 'text/plain']);
    }


    /**
     * @Route("/twig", name="twig")
     */
    public function helloTwig(): Response
    {
        $message = "Hello from Coding Twig";
        return $this->render('hello/index.html.twig', ["message" => $message]);
    }
}


The HelloController.php file has been changed, and a new route has been added. The function renders a Twig template this time. 

/**
 * @Route("/twig", name="twig")
 */
public function helloTwig(): Response
{


The twig path is mapped to the helloTwig() function.

$message = "Hello from Coding Twig";
return $this->render('hello/index.html.twig', ["message" => $message]);


Twig renders the 'hello/index.html.twig file, located in the templates directory. The render() method also accepts data; in our case, it is a message variable. The template engine merges data with a HTML structure.

{% extends 'base.html.twig' %}

{% block title %}Plain message{% endblock %}

{% block body %}
    {{ message }}
{% endblock %}


This is the Twig template file

{% extends 'base.html.twig' %}


The template inherits from the base.html.twig file, which has base markup that will be shared.

{{ message }}


A unique Twig syntax known as "" displays the contents of the variable.


<!DOCTYPE html>
<html>
    <head>
        <title>{% block title %}Welcome to Coding Ninjas!{% endblock %}</title>
        {% block stylesheets %}{% endblock %}
    </head>
    <body>
%body%
    </body>
</html>


The base.html.twig template contains code that is shared by other template files. It defines blocks that will be replaced in children templates.

$ curl 127.0.0.1:8000/twig
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Coding Ninjas</title>
      </head>
    <body>
          Hello from Coding Twig
    </body>
</html>

Examples of Symfony Framework 

Examples

1. Spotify 

The user accounts for Spotify, a streaming service with 286 million active users as of 2020, are managed by Symfony. Businesses can improve their solution and add new features by implementing open-source software that Symfony and PHP power.

2. Dailymotion 

Dailymotion is a streaming service similar to Spotify but only provides access to videos rather than music. The Dailymotion company built its website in PHP, but after a few years, they decided to switch to Symfony instead of the framework they had built. 

3. Trivago 

Another booking tool powered by Symfony and owned by the Trivago company serves millions of users and lets them compare hotel room rates. Symfony enables Internet users to have the best user experience possible when searching and comparing offers by building a variety of functionalities on the page.

4. Drupal Console 

Drupal Console is a debugging and event list creation tool built on the Symfony Console framework. The dependency injection container allows the event dispatcher access to all application events.

Must Read: Laravel Facades

Frequently asked questions 

In the MVC model, which depicts the organization of our corporate entities? 

Symfony's Model-View-Controller (MVC) architecture is the foundation of its web framework. The model depicts how our corporate entities are structured. The view presents the models to the user in the most appropriate manner, given the circumstances. The controller handles every request made by the user. 

How can console components be installed? 

The following command can be used to install the Console component.

Which component offers different ways to read and write information about objects and arrays using string notation?

The PropertyAccess component offers a number of ways to read and write details about objects and arrays in string notation. 

What component offers a range of options for parsing.env files?

Dotenv component provides various options to parse .env files and the variable defined in them to be accessible via getenv(), $_ENV, or $_SERVER.

Any URI typically has?

Any URI typically consists of three components Hostname segment, Path segment, and Query segment. 

Conclusion

In this blog, we discussed everything about Symfony Framework, its features and how it is beneficial for business. 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations. Read our blogs on aptitudecompetitive programminginterview questionsIT certificationsand data structures and algorithms for the best practice.

Previous article
Laravel Framework
Next article
Laravel Validation
Live masterclass