mark winkle
mark winkle

Reputation: 206

Zend framework 2 - How to call a function in view helpers

I have a view helper class

namespace Users\View\Helper;

use Zend\View\Helper\AbstractHelper;

class Userfunctions extends AbstractHelper
{
    protected $count = 0;

    public function test()
    {
       return 'testing';
    }


    public function __invoke($str, $find)
    {
        if (! is_string($str)){
            return 'must be string';
        }

        if (strpos($str, $find) === false){
            return 'not found';
        }

        return 'found';
    }


}

In module.config.php, i have called the view helper class, where Userfunctions is invoked in the view_helpers array.

'view_helpers' => array(  
        'invokables' => array(  
            'Userfunctions' => 'Users\View\Helper\Userfunctions',  
            // more helpers here ...  
        )  
    ),

What i am trying to achieve is, i need to call the test function()..

How can i achieve this..

I know by calling

echo $this->Userfunctions("me","e");

This will call the invode funcion and return found..but i need to call the test function.

Thanks,

Upvotes: 0

Views: 1137

Answers (2)

AlexP
AlexP

Reputation: 9857

Calling your plugin by name $this->userfunctions('me', 'e'); in the view is really just a short hand for the method Zend\View\Renderer\PhpRenderer::plugin('userfunctions') so using Bram Gerritsen answer is absolutely correct.

What I will add is that a number of the default view helpers follow the convention of checking the number of arguments passed to the __invoke function, if none are provided, an instance of the plugin is returned.

For example

namespace Users\View\Helper;

use Zend\View\Helper\AbstractHelper;

class Userfunctions extends AbstractHelper
{
    protected $count = 0;

    public function __invoke($str, $find)
    {
        if (0 === func_num_args()) {
            return $this;
        }

        return $this->render($str, $find);
    }

    public function render($str, $find)
    {
        if (! is_string($str)){
            return 'must be string';
        }

        if (strpos($str, $find) === false){
            return 'not found';
        }

        return 'found';
    }

    public function test()
    {
        return 'testing';
    }
}

You can then access all the methods in the view, as well as the default functionality of __invoke.

$this->userfunctions();
$this->userfunctions()->test();
$this->userfunctions()->render('me', 'e');

Upvotes: 1

Bram Gerritsen
Bram Gerritsen

Reputation: 7238

Try the following:

echo $this->plugin('Userfunctions')->test()

Upvotes: 2

Related Questions