2011-05-13 84 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類似,但您可以獲得更多實例,每個給定的鍵一個)。