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) :

<php

// ...

myControllerAction()
{
    //Actions that modify session
    // ...
 
    //We free session lock as no more session modifications will happen in next actions !
    $session = $this->get('session');
    $session->save();
    session_write_close();
 
    //Actions that don't modify session
    // ...
 
    $this->return('...');
}

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

1 comment :

Post a Comment

Comments are moderated before being published.