在 Zend Framework 中处理会话的最佳方式

2021-12-29 00:00:00 cookies php zend-framework

所以我开始使用 Zend 框架并希望实现一个站点范围的用户"会话......我可以从应用程序中的所有模块/控制器轻松访问它.

So I'm starting up in Zend framework and looking to implement a site-wide "User" session.... something I can easily access from ALL modules/controllers in the application.

我想,我应该在库中创建一个新的命名空间并扩展控制器,例如:

I'm like, should I make a new namespace in the library and extend the controller, like:

class MYCUSTOMLIB_Controller_Action extends Zend_Controller_Action
{
    protected $_userSession;

    function preDispatch(Zend_Controller_Request_Abstract $req)
    {
         $this->_userSession = new Zend_Session_Namespace('user');
    }
}

然后我所有的控制器/模块/等都从那里扩展?

ANd then have all my controllers/modules/etc extend from that?

或者我应该创建一个插件还是什么?你会如何让这个插件将用户会话传递给控制器​​?

Or should I create a Plugin or what? How would you go about making this plugin to pass the user session to the controller?

还是我在引导程序中执行?再次如何传递给控制器​​?

Or do I do it in the bootstrap?? Again how to pass to controller?

我也应该使用 Zend_Session_Namespace 或 Zend_Http_Cookie 以及如何加密和 xss 清理 cookie 还是自动完成?

Also should I use Zend_Session_Namespace or Zend_Http_Cookie and also how do I encrypt and xss clean the cookie or is that done automagically?

推荐答案

我也会在引导程序中初始化:

I would initialise in the bootstrap too:

//Bootstrap.php
protected function _initUserSession()
{
    return new Zend_Session_Namespace('user');
}

然后我会使用一个动作助手:

Then I would use an action helper:

// library/App/Controller/Action/Helper/Session.php
class App_Controller_Action_Helper_Session extends Zend_Controller_Action_Helper_Abstract
{
    function direct()
    {
        return $this->getFrontController()->getParam('userSession');
    }
}

您可以像这样在控制器中访问它:

You access it in your controller like this:

function indexAction()
{
    $session = $this->_helper->session;
}

相关文章