Monday, August 6, 2012

How to deal with asynchronous request with Symfony2 and other PHP frameworks

As well as most of PHP frameworks, Symfony2 manages user session by locking it during request treatment. It avoids concurrent access to session file but makes requests to be queued until session lock is freed...

This behaviour is really well explained in this post from Gareth McCumskey.

As Gareth describes his solution, we need to manually free session lock after all session modifications happen in the request treatment. Here is a pattern for controllers that handle AJAX calls (solution provided by Matt on stackoverflow) :


    // ...

    public function myControllerAction()
        //Actions that modify session
        // ...
        //We free session lock as no more session modifications will happen in next actions !
        $session = $this->get('session');
        // session_write_close(); // Only required before Symfony 2.1
        //Actions that don't modify session
        // ...

Here is the result for an action that process a 10 seconds sleep() :
Before :
After :