【问题标题】:zend view helper with multiple methods?具有多种方法的zend视图助手?
【发布时间】:2011-08-24 22:00:30
【问题描述】:
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)

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

谢谢

卢卡

【问题讨论】:

  • 感谢好友提出这个问题

标签: php zend-framework view-helpers


【解决方案1】:

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

$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
 }

【讨论】:

  • 想问你能不能做第二件事,很方便
  • “getHelper”方法对我不起作用。我必须在主辅助方法中返回对象以允许调用其他辅助方法。
【解决方案2】:

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

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

例如

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

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

【讨论】:

    【解决方案3】:

    这是对 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-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 2013-04-04
      相关资源
      最近更新 更多