Issues

ZF-8177: Registering helpers with views

Description

From a request on the FW-MVC mailing list, Zend_View should offer a way to register helper objects without relying on the plugin loader. This would allow for dependency injection, objects that don't follow the PEAR naming convention, and PHP 5.3 namespaces.

Comments

I'm putting together a patch that will allow registering custom helpers like this:

// Adding a custom helper $view = new Zend_View(); $helper = new MyCustomHelper(); $view->addHelper($helper, 'foo'); $view->foo(); // calls MyCustomHelper#foo()

// Overwriting a built-in helper $myUrlHelper = new MyUrlHelper(); $view->addHelper($myUrlHelper, 'url'); $view->url(); // calls MyUrlHelper#url();

Any thoughts on this?

I'm wondering now if it's a good idea also to include anonymous functions here as well (a la Zend_Validate_Callback). Of course, one could always create a "Callback" helper this way as well, which would accomplish the same purpose, without having to change things around too much.

What would that code look like? So far I have this:

/** * Registers a helper * * @param Zend_View_Helper_Abstract|object $helper * @param string $name * @return Zend_View_Abstract */ public function registerHelper($helper, $name) { if (!is_object($helper)) { throw new Zend_View_Exception('View helper must be an object.', $this); } $this->_helper[$name] = $helper; return $this; }

Sorry, forgot to add the code markup.. this should look better:


/**
 * Registers a helper
 *
 * @param Zend_View_Helper_Abstract|object $helper
 * @param string $name
 * @return Zend_View_Abstract
 */
public function registerHelper($helper, $name)
{
    if (!is_object($helper)) {
        throw new Zend_View_Exception('View helper must be an object.', $this);
    }
    $this->_helper[$name] = $helper;
    return $this;
}

What you have here seems to me to be sufficient for the main purpose of this feature (of course it must be tested!). As for adding in the anonymous function capabilities, you would probably have to change the __call method of Zend_View_Abstract, because that method is expecting a class and a method.

I don't have a CLA yet but I've attached the patch and passing unit test.

Please see attached files for fix and passing unit test.

Re-opening. Attaching a patch does not resolve an issue; committing code to the repository does. I'll review the patch for inclusion.

Thanks, Matthew. I don't have SVN commit privileges (that I know of). How can I submit a patch for review?

You just did. ;-)

Seriously, though, attaching patches to the issue tracker is the best way to do so. If you notice no action on one, feel free to bug the component lead (either directly, or via the zf-contributors mailing list).

Thanks!

Patches applied (with additional tests and slight changes in functionality) to trunk; will release with 1.10.