Inject filter into Zend_View
I wish to set some properties in MyFilter
with constructor injection but it seems impossible with Zend_View::addFilter(string $filter_class_name)
since it loads a new instance upon usage. MyFilter
implements Zend_Filter_Interface
.
Can I somehow inject an instance of a 开发者_JS百科filter to an instance of Zend_View
?
Closing since it (hopefully) will be pushed into 2.0, see ticket on JIRA.
You may pass object:
$filter = new Your_Filter($params); // implements Zend_Filter_Interface
$view->addFilter($filter);
You may get view instance from viewRenderer, e.g. using staticHelper.
Edit:
The other method may be:
class MyFilterSetup extends MyFilter implements Zend_Filter_Interface
{
public function __construct($params)
{
$this->_params = $params;
parent::__construct();
}
public function filter($string)
{
// .... $this->_params;
}
}
I'm not certain, but I don't think it's possible. Looking at the sourcecode setFilter()
and addFilter()
only accept the Filter Classname as a string. You cannot set any options, like you can in Zend_Form
for instance. What you could do though is:
class MyFilter implements Zend_Filter_Interface
{
protected static $_config;
public static setConfig(array $options)
{
self::_config = $options;
}
// ... do something with the options
}
and then you set the options where needed with MyFilter::setOptions()
, so when Zend_View
instantiates the Filter instance, it got what it needs to properly run the filter.
You can't in the 1.x branch, ticket is filed:
http://framework.zend.com/issues/browse/ZF-9718
Can't we create a custom view object extending Zend_View
that overrides the addFilter()
method to accept either a class or an instance. Then override the _filter()
method to deal with both types of filters - string and instance - that we have stored.
Why not assign the filter properties to the view, and then either set the properties when the view is set, or access the view directly in your filtering function? e.g.
$view->assign('MyFilterProperty', 'fubar');
and then in your filter class:
public function setView($aView)
{
$this->_property = $aView->MyFilterPropery;
}
It's kludgy, but it should get the job done.
精彩评论