如何在Zend Framework 2中引导会话

dra*_*ank 10 php session zend-framework2

在Zend Framework 2中启动和运行会话的最佳方法是什么?我已经尝试session_start()在我的index.php文件中进行设置,然后在任何自动加载器被引导之前运行,导致我的会话中存在不完整的对象.

在ZF1中,你可以通过在配置中添加一些选项来初始化会话,但是我对如何在ZF2中执行此操作感到茫然.

Sam*_*Sam 27

如果我理解正确的话,你想做的就是让你的会话在你的模块中正常运行?假设这是正确的,有两个单一的步骤.

1)创建config:module.config.php

return array(
    'session' => array(
        'remember_me_seconds' => 2419200,
        'use_cookies' => true,
        'cookie_httponly' => true,
    ),
);
Run Code Online (Sandbox Code Playgroud)

2)开始你的会话:Module.php

use Zend\Session\Config\SessionConfig;
use Zend\Session\SessionManager;
use Zend\Session\Container;
use Zend\EventManager\EventInterface;

public function onBootstrap(EventInterface $evm)
{
    $config = $evm->getApplication()
                  ->getServiceManager()
                  ->get('Configuration');

    $sessionConfig = new SessionConfig();
    $sessionConfig->setOptions($config['session']);
    $sessionManager = new SessionManager($sessionConfig);
    $sessionManager->start();

    /**
     * Optional: If you later want to use namespaces, you can already store the 
     * Manager in the shared (static) Container (=namespace) field
     */
    Container::setDefaultManager($sessionManager);
}
Run Code Online (Sandbox Code Playgroud)

\ Zend\Session\Config\SessionConfig的文档中查找更多选项

如果您也想存储cookie,请参阅此问题.感谢Andreas Linden最初的回答 - 我只是复制粘贴他的.

  • 您能解释一下如何在每次关闭浏览器时将ZF2 Session设置为自动销毁吗?标准方法是设置`cookie_lifetime = 0`.但是使用ZF2它不起作用.它不会破坏浏览器关闭的会话.此外,如果我设置`remember_me_seconds = 1`(零抛出异常)它也不起作用 - 关闭浏览器后,会话中所有信息都安全存在.如何在ZF2中设置这样的选项?谢谢. (2认同)