ZF2 - How can i call a function of a custom class

2019-08-07 16:10发布

i've created a custom service as php class ( ServiceClass ) with some functions ( generateInfo() ) and i'm looking for a way to call this function from other views

thanks for help.

1条回答
姐就是有狂的资本
2楼-- · 2019-08-07 17:05

You can create your own View Helper

namespace MyModule\View\Helper;

use Zend\View\Helper\AbstractHelper;

class MyHelper extends AbstractHelper
{       
    public function __invoke()
    {
        return $this;
    }

    public function render($arg1, $arg2)
    {
        return 'My Parametrizable Html ' . $arg1 . ' ' . $arg2;
    }

    public function generateInfo()
    {
        return 'Your HTML goes here';
    }
}

Now create an entry in the module.config.php for that helper:

'view_helpers' => array(
    'invokables' => array(
        'myHelper' => 'MyModule\View\Helper\MyHelper',
    ),
),

And now you can call it in your views:

<?php echo $this->myHelper()->render($arg1, $arg2); ?>

And for calling the generateInfo():

<?php echo $this->myHelper()->generateInfo(); ?>

You can also call it from a controller:

$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
$myHelper = $viewHelperManager->get('myHelper');

Without View Helper

Not the best practice because this generates repeated code but, if you do not want to create a View Helper, then you can always create an instance of your service in a controller and then pass it to the View.

查看更多
登录 后发表回答