Sco*_*tTx 5 php session zend-framework zend-framework3
我正在尝试设置一个 Zend 框架 3 MVC Web 应用程序来使用会话存储。根据本网站的信息——
这一切都很好。我在我的控制器中获得了会话变量,我可以将数据保存到会话容器中。问题是,我保存到容器的数据在后续调用中不存在。我正在从一个页面保存搜索条件并重定向到第二个页面以进行搜索并返回结果。当我进入第二页时,会话数据不存在。
在 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,
],
];
Run Code Online (Sandbox Code Playgroud)
在 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);
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
修改了我的 IndexController 以添加构造函数方法
class IndexController extends AbstractActionController
{
private $session;
public function __construct(Container $session)
{
$this->session = $session;
}
Run Code Online (Sandbox Code Playgroud)
在 application\module.config.php 我有这个
'controllers' => [
'factories' => [
Controller\IndexController::class => Controller\Factory\IndexControllerFactory::class,
],
],
'session_containers' => [
'Books\Session'
],
Run Code Online (Sandbox Code Playgroud)
要在会话中存储某些内容,您可以按如下方式创建容器:
// Create a session container
$container = new Container('Books\Session');
$container->key = $value;
Run Code Online (Sandbox Code Playgroud)
要稍后从会话容器中检索某些内容,您必须创建一个具有相同名称的新容器:
// Retrieve from session container
$container = new Container('Books\Session');
$value = $container->key;
Run Code Online (Sandbox Code Playgroud)
据我所知,这对于 ZF2 和 ZF3 来说都是类似的,并且可以在StackOverflow 上的其他帖子中找到,或者例如这篇标题为“在 Zend Framework 2 中使用会话”的博客文章。
如果您创建一个新的会话Container管理器来存储或解析会话中的数据,如果您自己没有传递一个会话管理器,它将自动使用默认的会话管理器。
您可以在第 77 行的方法中AbstractContainer::__construct看到这一点。如果$manager传递给构造函数的是,null它将获得方法内的默认会话管理setManager器。
因此,要使用会话,您不需要进行大量手动配置。
如果这不能解决您的问题,请发表评论。