如何在部分中访问自定义视图助手?

时间:2013-03-21 18:31:40

标签: zend-framework2

有没有办法访问我的模块中注册的自定义视图助手,如下所示:

'fooBar' => 'Library\FooBar\FooBar'
像这样?

<p>This is partial...</p>
<p><?php echo $this->fooBar(); ?></p>

我可以在视图中使用fooBar视图助手,但在部分中我得到一个错误。这是我的助手:

class FooBar extends AbstractHelper
{

    public function __invoke($module)
    {
        return $this->getView()->myMethod();
    }

}

我的错误是:

Call to a member function myMethod() on a non-object

1 个答案:

答案 0 :(得分:0)

这对我有用。我在Module.php文件中配置了这样的视图助手。

//模块/ SRC /模块/视图/助手/ Authz.php //查看助手

    use Zend\View\Helper\AbstractHelper;



    class Authz extends AbstractHelper 
    {

    public function isAllowed()
{
}
    }

// Module.php

public function bootstrap(Event $e)
    {

    }
    public function onBootstrap($e)
    {

        $app = $e->getApplication();
        $serviceManager = $app->getServiceManager();


        $serviceManager->get('viewhelpermanager')->setFactory('Authz', function ($sm) use ($e)      {
           return new Authz($sm); //view helper
        });


    }

//部分 // view / layout / partials / leftnav.phtml

$userAllow = $this->Authz()->isAllowed(); 

//在布局中我调用了leftnav.phtml以上的部分内容。 //view/layout/layout.phtml

<?php echo $this->partial('partials/header', array('company_name' => 'CompanyName')); ?>

// config / module.config.php

'view_manager' => array(
        'template_path_stack' => array(
            'modulename' => __DIR__ . '/../view' ,
        ),
        'strategies' => array(
            'ViewJsonStrategy',
        ),

        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'partials/header'           => __DIR__ . '/../view/layout/partials/header.phtml',
            'partials/leftnav'           => __DIR__ . '/../view/layout/partials/leftnav.phtml',            
            'partials/contents-top'           => __DIR__ . '/../view/layout/partials/contents-top.phtml',            
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',    
        ),

    ),