2008年12月5日星期五

Re: [fw-mvc] Persistence of view helpers

-- Giorgio Sironi <piccoloprincipeazzurro@gmail.com> wrote
(on Friday, 05 December 2008, 05:30 PM +0100):
> If a view helper is istantiated, it will persist and be recycled when other
> calls to $this->helperName() are made. However, it's the broker that
> instantiates the helper and so I cannot pass anything in the constructor to
> modify my helper behaviour. For example I'd like to build a view helper that
> access a particular model (a simple name=>value table) but I do not want the
> helper to make queries when I jave already the model in the bootstrap and I can
> pass it in, nor instantiating another time the model in the view helper
> constructor.
> A static field is not a nice solution, it's already diffucult to test
> controllers; maybe I can subclass the broker or similar to add an addHelper()
> method like the Zend_Controller_Action_HelperBroker one. What can be a viable
> solution?

We have a number of view helpers in the standard distribution that have
similar needs. The solution we found was to return the helper instance
when no arguments are passed to the helper:

public function foo($arg1 = null, $arg2 = array())
{
if (0 == func_num_args()) {
return $this;
}

...
}

This way, you can then access additional methods of the helper in order
to setup state:

$view->foo()->setOptions($options);
$view->foo()->setModel($model);

Make sense?

--
Matthew Weier O'Phinney
Software Architect | matthew@zend.com
Zend Framework | http://framework.zend.com/

没有评论: