class My_View_Helper_Gender extends Zend_View_Helper_Abstract
{
public function Gender()
{
//
}
}
"The class method (Gender()) must be named identically to the concliding part
of your class name(Gender).Likewise,the helper's file name must be named
identically to the method,and include the .php extension(Gender.php)"
(Easyphp websites J.Gilmore)
My question is: Can A view Helpe开发者_如何学编程r contain more than one method?And can I call other view helpers from within my helper?
thanks
Luca
Yes, helpers can contain additional methods. To call them, you have to get hold of the helper instance. This can be achieved either by getting a helper instance in the View
$genderHelper = $this->getHelper('Gender');
echo $genderHelper->otherMethod();
or by having the helper return itself from the main helper method:
class My_View_Helper_Gender extends Zend_View_Helper_Abstract
{
public function Gender()
{
return $this;
}
// … more code
}
and then call $this->gender()->otherMethod()
Because View Helpers contain a reference to the View Object, you can call any available View Helpers from within a View Helper as well, e.g.
public function Gender()
{
echo $this->view->translate('gender');
// … more code
}
There is no such provision but you can customize it.
May be you can pass the first parameter as function name and call it.
e.g.
$this->CommonFunction('showGender', $name)
here showGender will be function defined in CommonFunction class and $name will be parametr
This is modification of Gordon's suggestion to be able to use more instances of the helper (each with own properties):
class My_View_Helper_Factory extends Zend_View_Helper_Abstract {
private static $instances = array();
private $options;
public static function factory($id) {
if (!array_key_exists($id, self::$instances)) {
self::$instances[$id] = new self();
}
return self::$instances[$id];
}
public function setOptions($options = array()) {
$this->options = $options;
return $this;
}
public function open() {
//...
}
public function close() {
//...
}
}
You can use helper this way:
$this->factory('instance_1')->setOptions($options[1])->open();
//...
$this->factory('instance_2')->setOptions($options[2])->open();
//...
$this->factory('instance_2')->close();
//...
$this->factory('instance_1')->close();
Edit: This is a design pattern called Multiton (like Singleton, but you can get more instances, one per given key).
精彩评论