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


Zend framework 2 : Service locator in view helper

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

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);
    }
}

我尝试了解决方案,给出这里的链接

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

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);
    }
}

首先,你的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);
    }
}

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

不要将ServiceLocator作为依赖项使用

当你依赖ServiceManager时,你就陷入了糟糕的设计。您的类将具有未知类型的依赖关系,并且它们是隐藏的。当你的类需要一些外部数据时,让它通过__construct()直接可用,不要通过注入ServiceManager来隐藏依赖关系。