Zend框架2:视图助手中的服务定位器

时间:2014-05-08 01:58:43

标签: php zend-framework2 view-helpers service-locator

我试图访问视图助手中的服务定位器,以便我可以访问我的配置。我使用这个视图助手来表示递归函数,所以我不知道在哪里声明服务定位器。

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use CatMgt\Model\CategoryTable as RecursiveTable;

class CategoryRecursiveViewHelper extends AbstractHelper
{
    protected $table;

    public function __construct(RecursiveTable $rec)
    {
        $this->table = $rec; 
    }

    public function __invoke($project_id, $id, $user_themes_forbidden, $level, $d, $role_level)
    {

       $config = $serviceLocator->getServiceLocator()->get('config');

       //So i can access $config['templates']

       $this->__invoke($val->project_id, $id, $user_themes_forbidden, $level, $d, $role_level);

    }

}

我尝试了这里的解决方案link

但它没有帮助,这样做是否可以?

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use CatMgt\Model\CategoryTable as RecursiveTable;
use Zend\View\HelperPluginManager as ServiceManager;

class CategoryRecursiveViewHelper extends AbstractHelper
{
    protected $table;
    protected $serviceManager;

    public function __construct(RecursiveTable $rec, ServiceManager $serviceManager)
    {
        $this->table = $rec; 
        $this->serviceManager = $serviceManager;
    }

    public function __invoke($project_id, $id, $user_themes_forbidden, $level, $d, $role_level)
    {

       $config = $this->serviceManager->getServiceLocator()->get('config');

       //So i can access $config['templates']

       $this->__invoke($val->project_id, $id, $user_themes_forbidden, $level, $d, $role_level);

    }

}

1 个答案:

答案 0 :(得分:16)

首先,您的ViewHelper是一个无限循环,您的应用会像那样崩溃。您在__invoke内拨打__invoke - 这无效。

注册具有依赖关系的ViewHelper

首先,您要写下您的ViewHelper

class FooBarHelper extends AbstractHelper
{
    protected $foo;
    protected $bar;

    public function __construct(Foo $foo, Bar $bar)
    {
        $this->foo = $foo;
        $this->bar = $bar;
    }

    public function __invoke($args)
    {
        return $this->foo(
            $this->bar($args['something'])
        );
    }
}

接下来注册ViewHelper。因为它需要依赖,您需要使用工厂作为目标。

// module.config.php
'view_helpers' => [
    'factories' => [
        'foobar' => 'My\Something\FooBarHelperFactory'
    ]
]

目标现在是工厂 - 类,我们还没有写。所以继续它:

class FooBarHelperFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $sl)
    {
        // $sl is instanceof ViewHelperManager, we need the real SL though
        $rsl = $sl->getServiceLocator();
        $foo = $rsl->get('foo');
        $bar = $rsl->get('bar');

        return new FooBarHelper($foo, $bar);
    }
}

现在,您可以在任何视图文件中通过ViewHelper使用$this->foobar($args)

不要将ServiceLocator用作依赖

每当你依赖ServiceManager作为依赖时,你就会陷入糟糕的设计中。您的类将具有未知类型的依赖项,并且它们是隐藏的。每当您的课程需要一些外部数据时,请直接通过__construct()将其提供,并且不要通过注入ServiceManager来隐藏相关性。