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)

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

谢谢

卢卡

4

3 回答 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()

因为 View Helpers 包含对 View Object 的引用,所以您也可以从 View Helper 中调用任何可用的 View Helpers,例如

 public function Gender()
 {
     echo $this->view->translate('gender');
     // … more code
 }
于 2011-05-13T12:45:38.530 回答
0

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

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

例如

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

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

于 2011-05-13T12:45:47.703 回答
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,但您可以获得更多实例,每个给定键一个)。

于 2013-05-21T14:03:55.877 回答