【问题标题】:zend framework 3 session not workingzend 框架 3 会话不工作
【发布时间】:2017-04-24 05:54:43
【问题描述】:

我正在尝试设置一个 zend 框架 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'
],

【问题讨论】:

    标签: php session zend-framework zend-framework3


    【解决方案1】:

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

    // 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 的工作方式类似,可以在 other posts on StackOverflow 或例如 this blog post with the title Using Sessions in Zend Framework 2 中找到。

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

    你可以看到here in the AbstractContainer::__construct method on line 77。如果传递给构造函数的$managernull,它将在the setManager method 中获得默认会话管理器。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 2011-05-26
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2010-12-02
      • 2012-08-05
      • 2010-12-29
      相关资源
      最近更新 更多