Google News
logo
Symfony Interview Questions
Symfony is a set of PHP Components and a leading PHP framework to create websites and dynamic web applications. Symfony is an open-source web application framework. It follows the MVC design pattern and is released under the MIT License.
Symfony framework has the following benefits, such as :
 
* Fast development
* MVC Pattern
* Unlimited user flexibility
* Expandable
* It is a stable and sustainable framework
* It has a better user control
Some general rules that we follow :
 
* Action methods must have the Action suffix
* Action methods should return a valid response object
* Only action methods should be public
* Controller method should be short
Symfony bundle are very similar to plugins or packages in other frameworks or CMS. In Symfony, everything is a bundle from core framework components to code you write.The bundle gives the flexibility to use pre-built features packaged in third-party bundles or to create and distribute your own bundles. Generally, a Bundle contains the following directories and files.
 
Controller Directory : Contains controllers of the bundle
DependencyInjection Directory : Hold dependency injection, extension classes.
Resources/config/ Directory : Contains configuration files like routing.yaml.
Resources/views/ Directory : Contain view files of the bundle.
Resources/public/ Directory : Contains static resources such as images, stylesheets of a bundle.
Tests/ Directory : Contains all test files for the bundle.
 
There are two types of bundles are available in Symfony :
 
* Application-specific bundles : only used to build your application.
* Reusable bundles : meant to be shared across many projects.
Symfony Components are a set of decoupled and reusable PHP libraries. It is open-source software that aims to speed up the creation and maintenance of web applications, replace repetitive coding tasks, build robust applications in an enterprise context, and give developers full control over the configuration.
You require the following server requirements to install and run the Symfony framework, such as :
 
* PHP 5.5.9 or greater
* Composer
* JSON enabled
* ctype enabled
* timezone should be set (default timezone will not work)
Symfony controller is a PHP function that obtains information from the HTTP request to construct and return an HTTP response. The response can vary and could be an XML document, an HTML page, a redirect, a 404 error, a serialized JSON array, or any other request.
To clear cache in Symfony you can use cache:pool:clear command. This command will delete all data from the project storage directory. By default, Symfony comes with 3 cache clearers. They are
 
* cache.global_clearer
* cache.system_clearer
* cache.app_clearer

The Symfony bundle is a group of files and directories that are organized into a specific structure.
 
To create a bundle in Symfony follow below steps:
 
Step1 : Choose a namespace. The namespace must contain the name of the vendor and bundle name. Something like Courseya\DemoBundle.
 
Step2 : Create an empty class named CourseyaDemoBundle and extend it to Bundle class.
 
Example :
namespace FreeTimeLearn\DemoBundle; 
use Symfony\Component\HttpKernel\Bundle\Bundle;  

class FreeTimeLearnDemoBundle extends Bundle { 
}
Step3 : Save the above class in src/Courseya/DemoBundle directory.
 
Step4 : Register the above class in the bundle list supported by the application in the AppKernel class.

Example :
public function registerBundles() { 
   $bundles = array( 
      // ... 
      // register your bundle 
      new FreeTimeLearn\DemoBundle\FreeTimeLearnDemoBundle(), 
   ); 
   return $bundles; 
}
Step5 : Use generate:bundle command to generate your bundle.
php bin/console generate:bundle --namespace = FreeTimeLearn/DemoBundle
That's all you have created your first bundle in Symfony.
Annotations in Symfony are used for configuration of validation and mapping Doctrine information. Annotations are easy and convenient to use. In Standard Edition of Symfony, we have two additional bundles SensioFrameworkExtraBundle and JMSSecurityExtraBundle which provide better support for annotations. Using these bundles you can use annotations for controller configuration, routing, cache, security, template, etc.
By default, Symfony uses a twig template engine. Twig is a flexible, fast, secure, and open-source template engine for PHP and originates its syntax from Jinja and Django templates. It is licensed under a BSD License and maintained by Fabien Potencier. However, you are free to use plain PHP code if you want.
A group of configurations used to run an application is described as an Environment in Symfony. This framework has two default environments :
 
Prod : It is used to optimize for executing an application on production.

Dev : It is used when an application is developed locally.
There are various Symfony framework applications, such as :
 
* Thelia
* Drupal 8
* Daily motion
In Symfony, the form of helper functions are given below :
 
* Form_start
* Form_end
* Text area
* Checkbox
* Input_password_tag etc,.
In Symfony Session, the class is used to work with sessions. This class can perform all functions of native PHP sessions. Below is an example of creating and removing sessions in Symfony.
 
* Creating Session in Symfony
$session = new Session();  
$session->start();  

*
Setting Session in Symfony
$session->set('user_id', 200);  
* Getting session in Symfony
$session->get('user_id');  

*
Removing / Destroying session in Symfony
$session->remove('user_id');  
If you have access to the command line, then you can use the php bin/console about the command to view the installed version of the Symfony framework. You can get the version of Symfony in the symfony/src/Symfony/Component/HttpKernel/Kernel.php file.
The form helpers provide a faster way to write form inputs in templates, especially for complex elements such as dates, drop-down lists, and rich text. Here are some form helper functions of Symfony framework,
 
* form_tag()
* input_tag()
* input_password_tag()
* input_hidden_tag()
* textarea_tag()
* input_file_tag()
* select_tag()
* options_for_select()
* checkbox_tag()
* submit_tag()
You can get current route in Symfony using following code :
$request->get("_route"); //OR with Twig {{ app.request.attributes.get('_route') }}
The five cache adapters are available in the Symfony framework.
 
* File system cache adapter
* Array cache adapter
* APCu cache adapter
* PHP files cache adapter
* Redis cache adapter
Directives are configuration options in Nginx. Each option has a name and parameters and must end with a semicolon (;).Directives are used to control Modules and divided into simple directives and block directives.
 
Below is the list of few Nginx Directives :
 
* absolute_redirect
* add_before_body
* auth_basic
* auth_jwt
* auth_http_timeout
* debug_connection
* fastcgi_cache_key
Symfony 2 is a full-stack web framework written in PHP. It is a reusable set of standalone, decoupled, and cohesive PHP components that solve web development problems. Symfony 2 introduced unique HTTP and HTTP cache handling by being an HTTP-centric request or response framework. It also allows full use of advanced features such as ESI to separate the different parts of your page or application.
 
Symfony 2 is powered out of the box by fast PHP-built Symfony reverse proxy, and for mid to large installations, a seamless upgrade to varnish provides a 10-20x speedup and a far more robust cache handling.
Here are the following innovations that provide Symfony 2, such as :
 
* Symfony2 uses the Dependency Injection pattern.
* Symfony2 is packaged as Distributions.
* Everything is a Bundle in Symfony2.
* Symfony2 eases the debugging of your application.
* Symfony takes security very seriously.
We can install Symfony2 using given following command :
 
In Windows :
php -r "readfile('https://symfony.com/installer');" > symphony  
In Linux and macOS System :
sudo mkdir -p /usr/local/bin    
sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony    
sudo chmod a+x /usr/local/bin/symfony
$request->query->get('paraemeter_name') method is used to get the request parameters in symfony2.
Kernel's class registerBundles() method is used to enable bundles in Symfony.
Request : The most common way to create a request is to base it on the current PHP global variables with createFromGlobals():
use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();
 
Which is almost equivalent to the more verbose, but also more flexible, __construct() call :
$request = new Request(
    $_GET,
    $_POST,
    [],
    $_COOKIE,
    $_FILES,
    $_SERVER
);
 
Accessing Request Data : A Request object holds information about the client request. This information can be accessed via several public properties :
 
request : equivalent of $_POST;
query : equivalent of $_GET ($request->query->get('name'));
cookies : equivalent of $_COOKIE;
attributes : no equivalent - used by your app to store other data (see below);
files : equivalent of $_FILES;
server : equivalent of $_SERVER;
headers : mostly equivalent to a subset of $_SERVER ($request->headers->get('User-Agent')).


Identifying a Request : In your application, you need a way to identify a request; most of the time, this is done via the "path info" of the request, which can be accessed via the getPathInfo() method :
// for a request to http://example.com/blog/index.php/post/hello-world
// the path info is "/post/hello-world"
$request->getPathInfo();
 
Simulating a Request : Instead of creating a request based on the PHP globals, you can also simulate a request :
$request = Request::create(
    '/hello-world',
    'GET',
    ['name' => 'Fabien']
);
The Request class should not be overridden as it is a data object that represents an HTTP message. But when moving from a legacy system, adding methods or changing some default behavior might help. In that case, register a PHP callable that is able to create an instance of your Request class :
use App\Http\SpecialRequest;
use Symfony\Component\HttpFoundation\Request;

Request::setFactory(function (
    array $query = [],
    array $request = [],
    array $attributes = [],
    array $cookies = [],
    array $files = [],
    array $server = [],
    $content = null
) {
    return new SpecialRequest(
        $query,
        $request,
        $attributes,
        $cookies,
        $files,
        $server,
        $content
    );
});

$request = Request::createFromGlobals();
Response : A Response object holds all the information that needs to be sent back to the client from a given request. The constructor takes up to three arguments: the response content, the status code, and an array of HTTP headers:
use Symfony\Component\HttpFoundation\Response;

$response = new Response(
    'Content',
    Response::HTTP_OK,
    ['content-type' => 'text/html']
);
 
This information can also be manipulated after the Response object creation :
$response->setContent('Hello World');

// the headers public attribute is a ResponseHeaderBag
$response->headers->set('Content-Type', 'text/plain');

$response->setStatusCode(Response::HTTP_NOT_FOUND);
When setting the Content-Type of the Response, you can set the charset, but it is better to set it via the setCharset() method :
$response->setCharset('ISO-8859-1');
Note that by default, Symfony assumes that your Responses are encoded in UTF-8.

Sending the Response  : Before sending the Response, you can optionally call the prepare() method to fix any incompatibility with the HTTP specification (e.g. a wrong Content-Type header):
$response->prepare($request);
Sending the response to the client is done by calling the method send() :
$response->send();
We can create action in Symfony 2 by using the following command :
public function indexAction()    
    {    
        return $this->render('user/index.html.twig', [ ]);    
    } 
Twing is a powerful templating language of Symfony. It performs whitespace control, sandboxing, and automatic HTML escaping. 
Routing configuration files are written in the following technology, such as :
 
* YAML
* XML
* PHP
In Symfony, the following syntax of EmailType is :
use Symfony\Component\Form\Extension\Core\Type\EmailType;     
   
$builder->add('token', EmailType::class, array(     
   
'data' => 'abcdef', )); 
The following syntax is used to check valid email addresses.
Use Symfony\Component\Validator\Constraints as Assert;

class Student {     
/**   
   * @Assert\Email(   
    * message = "The email '{{ value }}' is not a valid email.",   
     * checkMX = true   
      * )   
*/     
  protected $email;     
}
The following methods are used to handle an Ajax request on the server-side.
if ($request->isXmlHttpRequest()) {   
   // Ajax request      
} else {      
   // Normal request       
}
SessionInterface object set and get method is used to set and get sessions in Symfony2. For example:
public function sessionAction(SessionInterface $session)  
{  
    // store an attribute for reuse during a later user request  
    $session->set('user_id', 5);  
   // get the attribute set by another controller in another request  
    $user_id = $session->get('user_id');    
}​
 
In Symfony, we can create controller by extending AbstractActionController class. For example :
use Zend\Mvc\Controller\AbstractActionController; 
use Zend\View\Model\ViewModel;      
   
class IndexController extends AbstractActionController {
   public function indexAction() {     
      return new ViewModel();     
   }     
}
Some web sites have a "safe" mode to assist those who don't want to be exposed to content to which they might object. The RFC 8674 specification defines a way for user agents to ask for safe content to a server.
 
The specification does not define what content might be considered objectionable, so the concept of "safe" is not precisely defined. Rather, the term is interpreted by the server and within the scope of each web site that chooses to act upon this information.
 
Symfony offers two methods to interact with this preference :
 
* preferSafeContent();
* setContentSafe();

The following example shows how to detect if the user agent prefers "safe" content :
if ($request->preferSafeContent()) {
    $response = new Response($alternativeContent);
    // this informs the user we respected their preferences
    $response->setContentSafe();

    return $response;