Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add headers to every response

Tags:

symfony

silex

How can I "automatically" add a header to every response with Silex?

So far I have to do following with every response:

$app->post('/photos'), function () use ($app) {
    return $app->json(array('status' => 'success'), 200, array('Access-Control-Allow-Origin' => '*'));
});

Instead, I would like to use a before filter to send Access-Control-Allow-Origin: * automatically with every request:

// Before
$app->before(function () use ($app) {
    $response = new Response();
    $response->headers->set('Access-Control-Allow-Origin', '*');
});

// Route
$app->post('/photos'), function () use ($app) {
    return $app->json(array('status' => 'success')); // <-- Not working, because headers aren't added yet.
});
like image 419
John B. Avatar asked Jan 14 '13 00:01

John B.


1 Answers

You can use the after application middleware, this is the method signature:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app->after(function (Request $request, Response $response) {
    // ...
});

This way you get the Response object that you can freely modify.

like image 126
Maerlyn Avatar answered Jan 01 '23 23:01

Maerlyn