具有多个方法的Zend视图助手?

18
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)

我的问题是: 一个视图助手可以包含多个方法吗?我能够从自己的助手中调用其他视图助手吗?

谢谢

Luca


谢谢伙计询问这个。 - Roshan Wijesena
3个回答

38

是的,帮助程序可以包含额外的方法。要调用它们,您必须获取帮助程序实例。这可以通过在视图中获取帮助程序实例来实现。

$genderHelper = $this->getHelper('Gender');
echo $genderHelper->otherMethod();

或者通过从主辅助方法中使帮助器返回自身:

class My_View_Helper_Gender extends Zend_View_Helper_Abstract
{
  public function Gender()
  {
    return $this;
  }
  // … more code
}

然后调用$this->gender()->otherMethod()

因为视图助手包含对视图对象的引用,您可以在视图助手内部调用任何可用的视图助手,例如:

 public function Gender()
 {
     echo $this->view->translate('gender');
     // … more code
 }

我本来想问你能不能做第二件事,这样挺方便的。 - Ascherer
“getHelper”的方法对我不起作用。我必须在主帮助器方法中返回对象以允许调用其他帮助器方法。” - webkraller

0

目前没有这样的规定,但您可以自定义它。

也许您可以将第一个参数作为函数名称传递并调用它。

例如:

$this->CommonFunction('showGender', $name)

这里的 showGender 将是在 CommonFunction 类中定义的函数,$name 将是参数。


0

这是对Gordon建议的修改,以便能够使用更多实例的帮助程序(每个实例都有自己的属性):

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() {
       //...
    }
}

您可以这样使用辅助函数:

$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();

编辑:这是一种称为Multiton的设计模式(类似于Singleton,但您可以获得更多实例,每个实例对应一个给定的键)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接