views:

272

answers:

2

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?

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?

A: 

You should initialize your session in the bootstrap. You can either put it in the Zend_Registry and access it that way or from your controllers you can access your bootstrap by calling $this->getInvokeArg('bootstrap').

// in your controllers    
public function init()
{
    $bootstrap = $this->getInvokeArg('bootstrap');
    $this->_session = $bootstrap->getResource('session');
}
smack0007
+3  A: 

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;
}
Rob Allen
Are you sure about the View helper?
Goran Jurić
This looks like a View Helper and Action helper mix :) Do view helpers use direct method() too? For view helper it should be session(), shouldn't it?
takeshin
Sorry. It's supposed to be an action helper! I've updated the code.
Rob Allen