symfonysilex

Add headers to every response


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.
});

Solution

  • 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.