Oliver Bayes-Shelton
Oliver Bayes-Shelton

Reputation: 6292

Symfony 2 Symfony\Component\HttpFoundation HeaderBag headers

So in Symfony2 I need to do the following:

$response->headers->addCacheControlDirective();
$response->headers->addCacheControlDirective();
$response->headers->addCacheControlDirective();
$response->headers->addCacheControlDirective();

The above methods are inside:

namespace Symfony\Component\HttpFoundation;

class HeaderBag

I have it working by updating my app_dev.php and app.php and adding the following:

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);

$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('max-age', 0);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);

Is this the proper way to modify the headers of should I do something else ?

Kinda new to Symfony and I want to do everything the correct way.

Upvotes: 0

Views: 392

Answers (1)

M. Foti
M. Foti

Reputation: 3182

Your solution will work, but it isn't a best practice. One of the great powers of Symfony2 is his Event Based kernel, the better way IMO is to write a Listener on kernel.response Event for header changes. Moreover, for example, in this way you can check your route.

One hipster implementation could be found for the HttpCache Listener, give also a look to his service definition.

Upvotes: 1

Related Questions