Symfony HttpFoundation - My Favorite PHP Library

Symfony has become the default way I write PHP and I don't mean just the Symfony Full Stack but the stand-alone Symfony components as well. Symfony components are decoupled and reusable PHP libraries which can be used independently from the Symfony Framework.  The best part is that they are well supported, well documented and open sourced so you can just go and grab some of them ( I use composer for that part, you should too)!!!

In that shiny list of components, there is a component called HttpFoundation. The HttpFoundation component defines an object-oriented layer for the HTTP specification. As an OOP fan I absolutely love it and I am not the only one. Drupal, Symfony, phpBB, Laravel, Sculpin and many other PHP projects are using it and I can see why.

To better understand what this library does, we must think of how the HTTP protocol works. Laconically speaking, the client sends an HTTP request and the server responds with an HTTP response. PHP uses some built-in superglobal variables to represent the request($_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, etc) and some functions to represent the response(echo, print, header, setcookie, etc). That's ugly and not so object oriented.

HttpFoundation to the rescue!!!

Think of HttpFoundation as an object oriented wrapper over PHP's superglobal variables and functions. HttpFoundation provides us with many useful classes and methods, a full list can be found here. Τhe most likely to come across are the Request and Response classes which represent HTTP request and  response respectively.

Take a look at Drupal's front controller:

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;  //The Request class

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals(); //Request from PHP's superglobals

$response = $kernel->handle($request);
$response->send();   //Sends HTTP headers and content

$kernel->terminate($request, $response);

The Request::createFromGlobals() method creates and returns a new request object with values from PHP's superglobals($_GET, $_POST, $_COOKIE, $_FILES, etc). That's it, you have a request object full of information about the current status of your request, information like the request HTTP method, the URI, request parameters and everything else associated with the HTTP request, all organized in one place. 

I need to mention that Drupal's front controller is just an example I used and you don't need Drupal or any other framework, you can just use HttpFoundation in your custom PHP app in the way you need it.

Here is another example implementing super simple routing:

$request = Request::createFromGlobals();

$path = $request->getPathInfo();

if($path == '/'){
    // your response for / request
}elseif($path == '/about'){
    // your response for /about request 
}
else{
    // return a 404 response
}

The getPathInfo() method returns the path being requested, relative to the executed script. So we can check and run the the appropriate script. Seriously, the Request class provides useful constants, properties and methods that will make your life easier, you can take a look here.

So after you get the client request analyze it, make your calculations, it's time to return a response to the client. Here is where the Response object comes.

<?php

use Symfony\Component\HttpFoundation\Response;  //The Response class

// new Response object
$response = new Response(
    'This is so cool',
    Response::HTTP_OK,
    array('content-type' => 'text/html')
);

$response->send(); // Sends HTTP headers and content

The constructor takes up to three parameters:

  1. The content of the response, for example your html or your json array.

  2. The HTTP Status Code of your response. The Response class uses some constants for example Response::HTTP_OK holds the status code 200 which means everything is OK, so instead of writing the number you can just use that constant.

  3. An array of HTTP headers for your response.

If you need to return a json response there is a JsonResponse class that represents an HTTP response in JSON format.

Last, but not least the Response object contains the send() method which sends the HTTP headers and the content to the client. A full documentation of the Response class can be found here.

The HttpFoundation quickly became one of my "must have" PHP libraries as it is very easy to use and improves the quality of my code impressively. It is structure agnostic so you can use it in different architectures whether you are using MVC or just a single-file app. In addition, you can find HttpFoundation in many PHP projects like Drupal, Symfony and Laravel so learning the basics, will make you more familiar with these frameworks as well.

Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.