Fork me on GitHub

Kris Wallsmith

Freelance life artist. Discussing web development, Symfony, life, and death. Father of 3, widower of 1.

Mar 11


This is one of my favorite methods in all of Symfony2 and it’s buried in the docs. Take a moment to glory in its simplicity:

public function someHeavyAction(Widget $widget, Request $request)
    $response = new Response();

    if ($response->isNotModified($request)) {
        return $response;

    // do some heavy lifting
    $response->setContent($this->renderView(/* ... */));

    return $response;

As you can see, this method makes implementing cache validation a snap. Once you’ve determined what you are going to use for validation — a last-modified timestamp and/or an e-tag — set that value on a new response object and this method will take care of the rest.

It accepts the current request as an argument and compares the cache headers coming in on the request with those you have set on the response. If the method returns true simply return the 304 response. If the method returns false, generate a fresh response.

It’s this sort of method that makes the Symfony2 HttpFoundation component the clear choice for anyone working with PHP and HTTP.

  1. kriswallsmith posted this