liz
liz

Reputation: 830

how to get view object in a plugin?

I have a controller action helper where i save a user object into the view (in an init function) like this:

Zend_Layout::getMvcInstance()->getView()->user = $user;

I'd like to access the object in a preDispatch method of a controller plugin so I don't have to look up the user in the database. I tried doing so like this:

$user = Zend_Layout::getMvcInstance()->getView()->user;

But it's returning a null object. I'm hoping its because I'm doing this wrong and not because I've programmed a catch 22 inside my login logic. Is there another way to access the object?

Upvotes: 4

Views: 5115

Answers (2)

Pavel Tytyuk
Pavel Tytyuk

Reputation: 119

Yes, good approach is to have a singleton class for current logged in user; in such a case it will be accessible anywhere - plugins, views, forms.

Upvotes: -1

vascowhite
vascowhite

Reputation: 18440

I think putting the following methods into your action helper may help you here.

private $user

public function init()
{
    $this->user = new user();
}

public function preDispatch()
{
    $user = $this->user;
    //Do whatever you wish with the user object.
    // although you probably don't need to do anything.
}

public function direct()
{
    Zend_Layout::getMvcInstance()->getView()->user = $this->user;
    //alternatively just return the user object or whatever you want to do
}

Then once your helper is registered you can simply do $this->_helper->helperName() in your controller to put the user object into the view.

Mathew WeirO'Phiney has a good explanation of action helpers on devzone. Especially the purpose of the direct() method.

Upvotes: 6

Related Questions