Managing Session with Zend_Session_Namespace
January 28th, 2009This video covers the Zend_Session_Namespace class. It’s a short introduction to how we can use this object to simplify passing data from Zend_Controller action to another during a user’s stay on our web application.

A look at the IndexController.php file:
/**
* Description of IndexController
*
* @author zendcasts
*/
class IndexController extends Zend_Controller_Action
{
public function preDispatch()
{
$this->session = new Zend_Session_Namespace(‘default’);
if (isset($this->session->pageCounter))
$this->session->pageCounter++;
else
$this->session->pageCounter = 0;
}
public function indexAction()
{
$this->view->message = $this->session->pageCounter;
}
public function pagetwoAction()
{
$this->session->pageCounter = $this->session->pageCounter + 10;
$this->view->message = $this->session->pageCounter;
}
}
Hi,
excellent tutorial!
But could you explain why the preDispatch mathod is necessary?
I doesn’t work if I instantiate the session in another method but why?
Regards
Hi Jay,
preDispatch is the first method that’s called within the controller. instantiating session there is best since it occurs before any rendering of the controller takes place. Also, you have access to the Request Object by that point as well.
See http://framework.zend.com/manual/en/zend.controller.basics.html for details, let me know if you have any more questions.
Cheers
The example works fine.
I am trying to use the session variables nested.
When the sample code is applied in this structure:
application
modules
admin
controllers
views
This gives an exception.
I can use session[] which gives a warning.
What am I missing?
Correct me if I’m wrong, but my experimentation shows that if I am using the ActionStack to trigger some additional actions that reside in the index controller, they are fired on postDispatch, which will cause the preDispatch in your example to get fired multiple times.
I noticed this since my counter was incrementing by 3 each time. A check of my ActionStack plugin showed that my 2 xtra plugins were causing this.
Good work! I’m watching all the casts.
I think the better way to transport datas through the application is with Zend_Registry.
In ZF 1.10 when we run the command zf create project SessionEx, we will already get an public function init() in the IndexController. We can write all the code in preDispatch() function in here and it works well.
I also changed the init() to preDispatch() and it never complained.
So is init() the new preDispatch() which is kept for backward compatibility or is there any difference?