Reusable components

This is the first post of a series on Symfony2 standalone components. In the series  we’ll review some of the most important components which provide the basic functionality used to implement websites, such as routing, security, and forms.

Symfony2 changed the way PHP frameworks were architected allowing the developer to pick and choose which components to use instead of using the full-stack framework. Because Symfony2 is split into components, you can use the entire framework or just some of the pieces. These components, which are well written, well tested and interact nicely with each other are being used as building blocks for other frameworks such as Silex, Laravel and many others. Even the next version of Drupal will also make use of some components – unless you are one of the unhappy users behind Backdrop-.

The HttpFoundation component

The HttpFoundation defines an object-oriented layer for the HTTP specification. Basically, instead of getting the request information from the superglobal variables ($_GET, $_POST$_FILES…), you have a Request object with some useful methods to get information. The same approach is followed to generate a Response, handle sessions, and manage file uploads.

Installation

The recommended way to install the component is through Composer:

[json]
“require”: {
“symfony/http-foundation”: “v2.3.4″
}
[/json]

Simple demo

The best way to see it in action is through a simple example:

<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

require_once __DIR__.'/vendor/autoload.php';

$request = Request::createFromGlobals();
$html = sprintf('</pre><h1>Hello %s, this is a demo!</h1><pre>', $request->query->get('name', 'Raul'));
$response = new Response($html);
$response->headers->set("content-type", "text/html");
$response->send();

Let's see what this code does...

  1. The first two lines only import the fully qualified names of the Request and Response classes.
  2. Require the autoload file auto-generated by Composer.
  3. Create a Request object based on the superglobal arrays: $_GET, $_POST, $_COOKIE, $_FILES and $_SERVER.
  4. Generate the html code using a query string parameter named "name". For example, if we go to http://test/index.php?name=John, the html code will be "<h1>Hello John, this is a demo!</h1>". If no parameter is given, "Raul" is used by default.
  5. Then, create a Response object with the html content, as well as the header 'Content-type'.
  6. At the end, send the response to the client using the HTTP protocol.

Main benefits:

  • Object oriented approach.
  • Testable: requests can be mocked.
  • Security.
  • Extra goodies: headers are normalized (Request and Response), useful methods...

Request

Screen Shot 2013-09-20 at 2.34.32 PM

The Request object encapsulates an HTTP request and provides lots of useful methods. Some of them:

  • getClientIp(): Returns the client IP
  • getMethod(): Returns the HTTP method (GET, POST, PUT...)
  • getLanguages(): Returns an array of the languages understood by the client.

It also provides "parameter bags" to access directly the querystring/post parameters, server info, files, cookies and headers.

Response

Screen Shot 2013-09-20 at 2.36.25 PM

The Response object encapsulates an HTTP response. Some of the methods are:

  • setStatusCode(Response::HTTP_I_AM_A_TEAPOT): Sets the HTTP status code.
  • setCharset('utf-8'): Sets the charset of the response content
  • setContent('<h1>test</h1>'): Sets the response content

Some subclasses are provided to set redirections (RedirectResponse), create streamed responses (StreamedResponse), and serving binary files (BinaryFileResponse).

Session

The session system provides a simple but powerful object-oriented session management using session storage drivers.

<?php
use Symfony\Component\HttpFoundation\Session\Session;

$session = new Session();
$session->start();

// sets an attribute (persist between requests)
$session->set('id', 1);

// gets the same attribute
echo $session->get('id');

Media types

The component has a kind of "hidden" feature: a mime-type guesser. Even though it was originally created to manage file uploads, it can be used as a standalone class. This class makes use of individual guessers.

  • FileBinaryMimeTypeGuesser: tries to guess the mime-type using the 'file -b --mime' command. It's not available on Windows systems.
  • FileinfoMimeTypeGuesser: it uses Fileinfo to guess the mime-type.
<?php
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
require_once __DIR__.'/vendor/autoload.php';

$guesser = MimeTypeGuesser::getInstance();
echo $guesser->guess('image.png'); // prints 'image/png'

More info

Photo: Khennya Castel