我有这样的代码:
$sessionOptions = new SessionDbSavehandlerOptions();
$sessionOptions->setDataColumn('data')
->setIdColumn('id')
->setModifiedColumn('modified')
->setLifetimeColumn('lifetime')
->setNameColumn('name');
$application = $event->getApplication();
$serviceManager = $application->getServiceManager();
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$sessionTableGateway = new TableGateway('zf2_sessions', $dbAdapter);
$sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
$config = $serviceManager->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->setSaveHandler($sessionGateway);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
效果很好,但此代码位于onBootstrap()
文件中的Module.php
方法中。是否有更好的方法(地点?)来实现会话?控制器插件适用于Controller,那么这些是什么?
答案 0 :(得分:4)
我的建议是将其作为专用的低级模块。您可以将完整的配置和实例化封装到一个简单的模块中,您可以依赖该模块进行进一步的应用。
与我们处理mail,logging和cache完全相同(虽然缓存尚未完成)。在这些情况下,我们创建可以在应用程序服务中注入的服务。在你的情况下,我会把它作为一个监听器(在专用类中封装或不在你的onBootstrap()
方法中进行初始化。
一个小例子:
namespace MySession;
use Zend\Session\Container;
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$manager = $sm->get('session_manager');
$manager->start();
Container::setDefaultManager($manager);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'session_manager' => 'MySession\Service\SessionManagerFactory'
),
);
}
}
并将会话管理器的工厂逻辑封装在工厂类中:
namespace MySession\Service;
use Zend\ServiceManger\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
// Your imports further here
class SessionManagerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $sl)
{
$sessionOptions = new SessionDbSavehandlerOptions();
$sessionOptions->setDataColumn('data')
->setIdColumn('id')
->setModifiedColumn('modified')
->setLifetimeColumn('lifetime')
->setNameColumn('name');
$application = $event->getApplication();
$serviceManager = $application->getServiceManager();
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
$sessionTableGateway = new TableGateway('zf2_sessions', $dbAdapter);
$sessionGateway = new DbTableGateway($sessionTableGateway, $sessionOptions);
$config = $serviceManager->get('Configuration');
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->setSaveHandler($sessionGateway);
return $sessionManager;
}
}