Silex会话没有保存数据?

时间:2013-04-10 05:46:28

标签: php silex

找到this question后,我的Silex会话至少得到了一个ID,但我没有看到会话数据在不同的页面浏览量中保存:

require(__DIR__.'/vendor/autoload.php'); // Composer autoload

$app = new Silex\Application();
$app['debug'] = true;

$app['db'] = $app->share(function() { // Database connector as a service
    return new PDO('mysql:host=localhost;dbname=myawesome_db', 'user', 'paswd');
});

$app['session.db_options'] = array(
    'db_table'      => 'php_sessions',
    'db_id_col'     => 'session_id',
    'db_data_col'   => 'session_value',
    'db_time_col'   => 'session_time',
);

$app['session.storage.pdohandler'] = $app->share(function () use ($app) {
    return new Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler(
        $app['db'],
        $app['session.db_options'],
        $app['session.storage.options']
    );
});
$app['session.storage'] = $app->share(function() use ($app) {
    return new Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage(
        $app['session.storage.options'],
        $app['session.storage.pdohandler']
    );
});
$app->register(new Silex\Provider\SessionServiceProvider()); // Start session management
$app['session']->start();

$app->get('/session-set', function() use ($app) {
    $app['session']->set('foobar', 'test');
    $app['session']->save();
    $out = "User session is: ".$app['session']->getId()."<br />\n";
    $out .= "Session variable is: ".var_export($app['session']->get('foobar'), true)."<br />\n";
    return $out;
});
$app->get('/session-get', function() use ($app) {
    $out = "User session is: ".$app['session']->getId()."<br />\n";
    $out .= "Session variable is: ".var_export($app['session']->get('foobar'), true)."<br />\n";
    return $out;
});

$app->run(); // Off into the sunset

/session-set页面显示foobar会话变量的值,但/session-get页面没有。有谁能帮我弄明白为什么?

1 个答案:

答案 0 :(得分:0)

我的解决方案结果是PDO数据库连接未正确设置(其中一个列名称错误)。但是,默认情况下,PDO MySQL连接在出错时不会抛出异常,只会设置ErrorInfo()详细信息。一旦我打开异常抛出我的PDO连接,我发现错误并修复它。我还向Symfony提交了一个补丁,以确保会话PDO对象启用了异常抛出,以避免其他人遇到此问题。