Inject filter into Zend_View

658 Views Asked by At

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 filter to an instance of Zend_View?

Closing since it (hopefully) will be pushed into 2.0, see ticket on JIRA.

5

There are 5 best solutions below

0
On BEST ANSWER

You can't in the 1.x branch, ticket is filed:

http://framework.zend.com/issues/browse/ZF-9718

3
On

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.

2
On

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;
     }
}
1
On

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.

1
On

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.