简体   繁体   中英

Zend ViewHelper Sub Functions

I want to add more than one function to a ViewHelper. Usually there is one function named like the class and like the file name.

How can I add several functions into one ViewHelper?

Eg like this:

class Zend_View_Helper_MyMenuHelper extends Zend_View_Helper_Abstract
{
    public function Horizontal($parameter)
    {
         return "...";
    }
}

echo $this->MyMenuHelper()->Horizontal($parameter);

Alex was on the right path, but missed something in his answer: the actual myMenuHelper() method has to return the view helper itself, for this to work:

class Zend_View_Helper_MyMenuHelper extends Zend_View_Helper_Abstract
{
    public function myMenuHelper()
    {
        return $this;
    }

    public function horizontal() { ... }

    // more methods...
}

And then, as mentioned:

echo $this->myMenuHelper()->horizontal();

Sometimes you don't want to pass through the main method of a view helper, although it's not that bad for some kinds of logic. In that case, use getHelper() :

class Zend_View_Helper_MyMenuHelper extends Zend_View_Helper_Abstract
{
    public function myMenuHelper()
    {
        // some logic, maybe the main one
    }

    public function horizontal() 
    {    
        // some other logic
    }
}

The following examples bypass myMenuHelper() completely:

// in controller
$this->view->getHelper('MyMenuHelper')->horizontal();

// in view
$this->getHelper('MyMenuHelper')->horizontal();`

In some cases for example, I populate the view helper with some internal data in the controller , the call its main method directly in the view , which acts on that data.

// in controller
$this->view->getHelper('MyMenuHelper')->storeData($someArray);

// in view
$this->myMenuHelper(); // iterates over $someArray

try to start the function name with a lower case letter

        class Zend_View_Helper_MyMenuHelper extends Zend_View_Helper_Abstract
        {
                public function horizontal($parameter)
                {
                       return "...";
                }
        }

in the view:

        echo $this->myMenuHelper()->horizontal($parameter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM