11

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.
});
sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
John B.
  • 1,869
  • 5
  • 21
  • 21

1 Answers1

16

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.

Pier-Luc Gendreau
  • 11,989
  • 4
  • 51
  • 60
Maerlyn
  • 32,079
  • 17
  • 92
  • 82
  • I also needed to output a header for every request but just added it to my index.php, is the above method the better way to do this? – gunnx Jan 14 '13 at 15:14
  • Do you mean you added a simple `header()` call? You should do it in the `after()` handler like in my answer. – Maerlyn Jan 14 '13 at 16:36
  • Does this need to be at a certain place in the code? It is breaking my app for some reason. – Sam Selikoff Jun 01 '13 at 03:50
  • AFAIK you can define an after middleware anywhere. – Maerlyn Jun 01 '13 at 08:41
  • 1
    Simple `header` calls didn't work that great. Better to do something like this in the `after` block `$response->headers->set('key', 'value');` – Dex Feb 10 '17 at 13:41