gpt4 book ai didi

php - Zend 框架 2 : Service locator in view helper

转载 作者:可可西里 更新时间:2023-11-01 13:08:37 26 4
gpt4 key购买 nike

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

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

}

}

最佳答案

首先,您的 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。由于它需要依赖项,因此您需要使用 factory 作为目标。

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

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

永远不要将 ServiceLocator 作为依赖项使用

每当您依赖 ServiceManager 作为依赖项时,您就会陷入糟糕的设计。您的类将具有未知类型的依赖项,并且它们是隐藏的。每当您的类需要一些外部数据时,直接通过 __construct() 使其可用,并且不要通过注入(inject) ServiceManager 来隐藏依赖项。

关于php - Zend 框架 2 : Service locator in view helper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23531462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com