Symfony: 3 – Requests and responses

Requests and responses

Symfony provides two classes that allow you to interact with the HTTP request and response. The Request and Response classes are part of a standalone component included with Symfony called HttpFoundation. This component can be used entirely independently of Symfony and also provides classes for handling sessions and file uploads.

The Request class is a simple object-oriented representation of the HTTP request message. For example:

use Symfony\Component\HttpFoundation\Request;
 
$request = Request::createFromGlobals();
 
// the URI being requested (e.g. /about) minus any query parameters
$request->getPathInfo();
 
// retrieve GET and POST variables respectively
$request->query->get('foo');
$request->request->get('bar', 'default value if bar does not exist');
 
// retrieve SERVER variables
$request->server->get('HTTP_HOST');
 
// retrieves an instance of UploadedFile identified by foo
$request->files->get('foo');
 
// retrieve a COOKIE value
$request->cookies->get('PHPSESSID');
 
// retrieve an HTTP request header, with normalized, lowercase keys
$request->headers->get('host');
$request->headers->get('content_type');
$request->getMethod(); // GET, POST, PUT, DELETE, HEAD
$request->getLanguages(); // an array of languages the client accepts
 
$request = $this->getRequest();
$request->isXmlHttpRequest(); // is it an Ajax request?
$request->getPreferredLanguage(array('en', 'fr'));
$request->query->get('page'); // get a $_GET parameter
$request->request->get('page'); // get a $_POST parameter

The Request class has a public attributes property, which holds special data related to how the application works internally. The attributes holds the values returned by the matched route, like _controller, id (if you have an {id} wildcard), and even the name of the matched route (_route). The attributes property exists entirely to be a place where you can prepare and store context-specific information about the request.

// To get values for parameters in the path (eg /posts/{id})
$request->attributes->all();

Symfony also provides a Response class: a simple PHP representation of an HTTP response message. This allows your application to use an object-oriented interface to construct the response that needs to be returned to the client:

use Symfony\Component\HttpFoundation\Response;
 
$response = new Response();
$response->setContent('<html><body>
<h1>Hello world!</h1>
</body></html>');
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'text/html');
 
// prints the HTTP headers followed by the content
$response->send();
 
// create a simple Response with a 200 status code (the default)
$response = new Response('Hello '.$name, Response::HTTP_OK);
 
// create a JSON-response with a 200 status code
$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');

HttpFoundation

The HttpFoundation component defines an object-oriented layer for the HTTP specification. 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();

A Request object holds information about the client request. List of known 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
  • files: equivalent of $_FILES
  • server: equivalent of $_SERVER
  • headers: mostly equivalent to a sub-set of $_SERVER ($request->headers->get(‘User-Agent’))

Each property is a ParameterBag instance. All ParameterBag instances have methods to retrieve and update its data:

  • all(): Returns the parameters
  • keys(): Returns the parameter keys
  • replace(): Replaces the current parameters by a new set
  • add(): Adds parameters
  • get(): Returns a parameter by name
  • set(): Sets a parameter by name
  • has(): Returns true if the parameter is defined
  • remove(): Removes a parameter

The ParameterBag instance also has some methods to filter the input values. All getters takes up to three arguments: the first one is the parameter name and the second one is the default value to return if the parameter does not exist:

// the query string is '?foo=bar'
 
$request->query->get('foo');
// returns bar
 
$request->query->get('bar');
// returns null
 
$request->query->get('bar', 'bar');
// returns 'bar'

Leave a Reply