2011-05-13 58 views
17
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) 

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

感谢

卢卡

+0

感谢好友问这个 – 2013-01-17 10:43:42

回答

38

是,助手可以包含其他方法。要打电话给他们,你必须得到助手实例。这可以通过在视图得到一个帮助程序实例来实现

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

或具有助手从主helper方法返回本身:

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

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

由于View助手包含对视图对象的引用,您也可以从视图助手中调用任何可用的视图助手,例如

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

会问你是否可以做第二件事,很方便 – Ascherer 2011-05-15 11:13:17

+0

'getHelper'方法对我来说并不适用。我不得不在主帮助程序方法中返回对象,以允许调用其他帮助程序方法。 – webkraller 2012-06-21 16:33:08

+0

感谢兄弟,这有助于 – 2013-01-17 10:43:20

0

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

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

例如

$这个 - > CommonFunction( 'showGender',$名)

这里showGender将在CommonFunction类中的功能定义和$ name将parametr

0

这是戈登的建议进行修改,以便能够使用助手的多个实例(每个自己的属性):

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类似,但您可以获得更多实例,每个给定的键一个)。