Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^264) CHAPTER 17 ■ THE ZEND FRAMEWORK APPLIED
The redirector helper doesn’t implement either of the events, but uses its helper integration to
provide a convenient interface for redirection.
If you wish to write your own action helper, simply subclass Zend_ControllerAction
Helper_Abstract and implement as many methods as you find useful. To register your action
helper, call addHelper() on the HelperBroker:
Zend_Controller_Action_HelperBroker::addHelper(new YourHelperClass());
Alternatively, you can set a path where the HelperBroker can find all of your helpers with
addPath(). For example, add all helper classes in the path that start with the class prefix YourPrefix:
Zend_Controller_Action_HelperBroker::addPath('/path/to/helpers', 'YourPrefix');
To access a helper from an action, call $this->getHelper('YourHelperClass') as you have
done for previous examples involving FlashMessenger, Redirector, and ViewRenderer.


Writing View Helpers


You can also create your own view helpers, but you should take care to make sure that a helper
is an appropriate choice. Ideally, view helpers should be used for repetitive tasks, and only as a
way to gain convenience when working with common view data. They must not be used to
circumvent processing in your actions, as that would significantly reduce the benefits of using
an MVC framework and blur the line between what is a controller and what is a view.
To create your own view helper, create a class with a named prefix of Zend_View_Helper_
and place it in ./views/helpers. Listing 17-5 shows how to create a view helper that returns the
current date.

Listing 17-5. A Simple View Helper

<?php
class Zend_View_Helper_CurrentDate {
public function currentDate() {
return date("D M j");
}
}

Inside a view, you can use your view helper by calling $this->currentDate(), as shown in
Listing 17-6.

Listing 17-6. A View Script Using a Custom Helper

<html>
<body>
<p>Current Date: <?php echo $this->currentDate(); ?></p>
</body>
</html>

McArthur_819-9.book Page 264 Friday, February 29, 2008 8:03 AM

Free download pdf