Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 PDO Session with Flashbag

I'm using Symfony 2.3.1 (this issue was also present in 2.2) with session.handler.pdo, but when I add a flash bag message like so:

$this->get('session')->getFlashBag()->add(
     'success', "Your message has been sent."
);                

return $this->redirect($this->generateUrl('home'));

It does not show on the home page after the redirect until I press refresh, then it shows up. So its taking 2 requests to be displayed. If I change the session storage back to native this problem is gone. Any ideas why this is happening?

I use the following to print the messages in Twig

{% for flashMessage in app.session.flashbag.get('success') %}
     {{flashMessage}}
{% endfor %} 

and my services is the same as the documentation as follows:

services:
    pdo:
        class: PDO
        arguments:
            dsn:      "mysql:dbname=%database_name%"
            user:     %database_user%
            password: %database_password%
        calls:
            - [setAttribute, [3, 2]] # \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION

    session.handler.pdo:
        class:     Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
        arguments: ["@pdo", %pdo.db_options%]
like image 581
Greg Somers Avatar asked Nov 02 '22 19:11

Greg Somers


2 Answers

I had similar in memcache session. There may be race condition.

When write flash and redirect sequence can be:

-client redirects    | -DB saves record
-client accesses     |
 the redirected URL  |
                     | -DB completes saving
-client refreshes    |

In my case workaround was adding below into AppKernel.php.

public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
    $response = parent::handle($request, $type, $catch);

    if ($type == HttpKernelInterface::MASTER_REQUEST) {
        if ($this->getContainer()->get('session')->isStarted()) {
            //explicitly save session before returning $response
            $this->getContainer()->get('session')->save();
        }
    }

    return $response;
}
like image 169
denkiryokuhatsuden Avatar answered Nov 09 '22 18:11

denkiryokuhatsuden


I've the same problem when using swiftmailer, and I got a quickfix for this problem.

If you are using SwiftMailer in this action, try to remove the spool line in your config file.

Thats not the best way to fix it, but it works.

Still working and thinking in a better solution here...

like image 35
grogers Avatar answered Nov 09 '22 18:11

grogers