ZF2 - How can i call a function of a custom class php from a view? [closed]

六月ゝ 毕业季﹏ 提交于 2019-12-11 10:41:15

问题


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:


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.



来源:https://stackoverflow.com/questions/28815947/zf2-how-can-i-call-a-function-of-a-custom-class-php-from-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!