ZF2 SessionManager用法

时间:2013-12-17 16:19:16

标签: php zend-framework2

我是ZF2的新手,并不习惯如何做事。我想使用会话来跟踪用户(记住我)。我把这段代码放在班上的一部分:

$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);

好的,到目前为止一切顺利。当我尝试:

var_dump($sessionManager->getStorage());

我得到了预期的数据。

在我的程序的另一部分,我想再次检索我的数据(有点像容器):

$sessionManager = new \Zend\Session\SessionManager();
var_dump($sessionManager->getStorage());

这只返回一个空对象。 我想这是由于“新”,我认为我必须以不同的方式实现SessionManager,但是如何?我不知道。这就是我想出的:

在我的模块中,我现在有:

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

'session' => array(
    'remember_me_seconds' => 2419200,
    'use_cookies' => true,
    'cookie_httponly' => true,
),

但如何处理?如何获取sessionManager的实例?

2 个答案:

答案 0 :(得分:14)

没有详细记录的SessionManagerFactory(zf2 api doc)和SessionConfigFactory(zf2 api doc)。有了这些实例化SessionManager非常简单,只需将这些工厂放入ServiceManager配置:

'service_manager' => [
    'factories' => [
        'Zend\Session\SessionManager' => 'Zend\Session\Service\SessionManagerFactory',
        'Zend\Session\Config\ConfigInterface' => 'Zend\Session\Service\SessionConfigFactory',
    ],
],

和模块配置将会话选项放在session_config键下:

'session_config' => [
    'remember_me_seconds' => 2419200,
    'use_cookies' => true,
    'cookie_httponly' => true,
],

就是这样,现在你可以从任何地方的服务定位器中获取SessionManager,例如在控制器中:

/** @var Zend\Session\SessionManager $sm */
$sessionManager = $this->serviceLocator->get('Zend\Session\SessionManager');

从2.2版本的Zend Framework(related pull request)开始提供。

答案 1 :(得分:2)

在我的项目中,我使用其他来源的示例(书籍或官方文档,忘了)。

Module.php个文件:

namespace Application;

class Module
{
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Zend\Session\SessionManager' => function ($sm){
                    $config = $sm->get('config');
                    if (isset($config['session'])){
                        $session_config = $config['session'];

                        $sessionConfig = null;
                        if (isset($session_config['config'])){
                            $class = isset($session_config['config']['class'])
                                ? $session_config['config']['class']
                                : 'Zend\Session\Config\SessionConfig';
                            $options = isset($session_config['config']['options'])
                                ? $session_config['config']['options']
                                : array();
                            $sessionConfig = new $class();
                            $sessionConfig->setOptions($options);
                        }

                        $sessionStorage = null;
                        if (isset($session_config['storage'])){
                            $class = $session_config['storage'];
                            $sessionStorage = new $class();
                        }

                        $sessionSaveHandler = null;
                        if (isset($session_config['save_handler'])){
                            // class should be fetched from service manager
                            // since it will require constructor arguments
                            $sessionSaveHandler = $sm->get($session_config['save_handler']);
                        }

                        $sessionManager = new SessionManager(
                            $sessionConfig,
                            $sessionStorage,
                            $sessionSaveHandler
                        );

                        if (isset($session_config['validator'])){
                            $chain = $sessionManager->getValidatorChain();
                            foreach ($session_config['validator'] as $validator){
                                $validator = new $validator();
                                $chain->attach('session.validate', array(
                                    $validator,
                                    'isValid'
                                ));
                            }
                        }
                    } else {
                        $sessionManager = new SessionManager();
                    }
                    Container::setDefaultManager($sessionManager);
                    return $sessionManager;
                },
            ),
        );
    }
}

我的config/autoload/global.php配置文件:

return array(
    'session' => array(
        'config' => array(
            'class' => 'Zend\Session\Config\SessionConfig',
            'options' => array(
                'use_cookies' => true,
            ),
        ),
        'storage' => 'Zend\Session\Storage\SessionArrayStorage',
        'validators' => array(
            array(
                'Zend\Session\Validator\RemoteAddr',
                'Zend\Session\Validator\HttpUserAgent',
            ),
        ),
    ),
);

从会话中获取user_id

$sessionStorage = $sm->get('Zend\Session\SessionManager')
    ->getStorage();
$user_id = $sessionStorage->user_id;