繁体   English   中英

zend Framework 3会话不起作用

[英]zend framework 3 session not working

我正在尝试设置一个zend framework 3 MVC Web应用程序以使用会话存储。 遵循本网站的信息-

https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Working_with_Sessions/PHP_Sessions.html

一切都很好。 我在控制器中获取了会话变量,并且可以将数据保存到会话容器中。 问题是,我保存到容器的数据在后续调用中不存在。 我要从一页保存搜索条件,然后重定向到另一页以执行搜索并返回结果。 当我进入第二页时,会话数据不存在。

在config \\ global.php中,我有-

return [
    'session_config' => [
        // Cookie expires in 1 hour
        'cookie_lifetime' => 60*60*1,
        // Stored on server for 30 days
        'gc_maxlifetime' => 60*60*24*30,
        ],
    'session_manager' => [
        'validators' => [
            RemoteAddr::class,
            HttpUserAgent::class,
            ],
        ],
    'session_storage' => [
        'type' => SessionArrayStorage::class,
    ],
];

在application \\ module.php中,我修改了onBoostrap

public function onBootstrap(MvcEvent $event)
{
    $application = $event->getApplication();
    $svcMgr = $application->getServiceManager();

    //  Instantiate the session manager and
    //  make it the default one
    //
    $sessionManager = $svcMgr->get(SessionManager::class);
 }

我创建了一个IndexControllerFactory

class IndexControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container,
                             $requestedName, array $options = null)
    {
        // Get access to session data
        //
        $sessionContainer = $container->get('Books\Session');
        return new IndexController($sessionContainer);
    }
}

修改了我的IndexController以添加构造函数方法

class IndexController extends AbstractActionController
{
    private $session;

    public function __construct(Container $session)
    {
        $this->session = $session;
    }

在application \\ module.config.php我有这个

'controllers' => [
    'factories' => [
        Controller\IndexController::class => Controller\Factory\IndexControllerFactory::class,
    ],
],
'session_containers' => [
    'Books\Session'
],

要在会话中存储内容,可以按如下方式创建容器:

// Create a session container
$container = new Container('Books\Session');
$container->key = $value;

要稍后从会话容器中检索内容,您必须创建一个具有相同名称的新容器:

// Retrieve from session container
$container = new Container('Books\Session');
$value = $container->key;

据我所知,这对于ZF2和ZF3都类似,并且可以在StackOverflow上的其他帖子中找到,例如在Blog标题为“在Zend Framework 2中使用会话”中

如果您创建一个新的Container来存储或解析会话中的数据,那么如果您自己没有通过Container ,它将自动使用默认的会话管理器。

您可以在第77行的AbstractContainer::__construct方法中看到这一点 如果传递给构造函数的$managernull ,它将setManager方法中获取默认的会话管理器。

因此,使用会话无需进行大量手动配置。

如果那不能解决您的问题,请发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM