问题描述
我是 ZF2 的新手,不太习惯如何做事.我想使用会话来跟踪用户(记住我).我在课堂上的一个部分有这段代码:
I am new to ZF2 and not quite used to how to do stuff. I want to use session to keep track of an user (remember me). I had this code in one part of my class:
$sessionManager = new \Zend\Session\SessionManager();
$sessionManager->rememberMe($time);
// i want to keep track of my user id too
$populateStorage = array('user_id' => $user->getId());
$storage = new ArrayStorage($populateStorage);
$sessionManager->setStorage($storage);
好的,到目前为止一切顺利.当我尝试:
Ok, so far so good. When i try:
var_dump($sessionManager->getStorage());
我得到了预期的数据.
在我程序的另一部分,我想再次检索我的数据(有点像容器):
In another part of my program, i want to retreive my data again (a bit like containers):
$sessionManager = new \Zend\Session\SessionManager();
var_dump($sessionManager->getStorage());
这只会返回一个空对象.我想这是由于新",我认为我必须以不同的方式实现 SessionManager,但是如何实现?我不知道.这是我想出的:
This only returns an empty object.I guess this is due to the "new" and i think i have to implement SessionManager in a different way, but how? I do not know. This is what i came up with:
在我的模块中,我现在有:
In my Module i now have:
public function onBootstrap(\Zend\Mvc\MvcEvent $e)
{
$config = $e->getApplication()
->getServiceManager()
->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
在我的 module.config 中:
In my module.config:
'session' => array(
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
),
但是如何进行呢?如何获取 sessionManager 的实例?
But how to procede? How do i get the instance for my sessionManager?
推荐答案
没有很好的文档记录 SessionManagerFactory (zf2 api doc) 和 SessionConfigFactory (zf2api 文档).使用这些实例化 SessionManager 非常简单,只需将这些工厂放入您的 ServiceManager 配置中:
There is not well documented SessionManagerFactory (zf2 api doc) and SessionConfigFactory (zf2 api doc). With those is instantiate SessionManager very easy, just put these factories to your ServiceManager configuration:
'service_manager' => [
'factories' => [
'Zend\Session\SessionManager' => 'Zend\Session\Service\SessionManagerFactory',
'Zend\Session\Config\ConfigInterface' => 'Zend\Session\Service\SessionConfigFactory',
],
],
并在模块配置中将您的会话选项放在 session_config 键下:
and to module configuration put your session options, under the session_config key:
'session_config' => [
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
],
就是这样,现在您可以从服务定位器的任何地方获取 SessionManager,例如在控制器中:
and that's it, now you can grab SessionManager from service locator anywhere, for example in controller:
/** @var Zend\Session\SessionManager $sm */
$sessionManager = $this->serviceLocator->get('Zend\Session\SessionManager');
自 Zend Framework 2.2 版起可用(相关拉取请求).
This is available as of 2.2 version of Zend Framework (related pull request).
这篇关于ZF2 SessionManager 使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!