Bri*_*euc 6 php view-helpers service-locator zend-framework2
我正在尝试访问视图助手中的服务定位器,以便我可以访问我的配置.我正在使用此视图助手进行递归功能,因此我不知道在哪里声明服务定位器.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我试过解决方案给这里链接
但它没有帮助,这样做是否可行?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 16
首先,你ViewHelper是一个无限循环,你的应用程序会像那样崩溃.你打电话给__invoke内__invoke- 这只是无法奏效.
首先,你会写下你的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'])
);
}
}
Run Code Online (Sandbox Code Playgroud)
接下来注册了ViewHelper.因为它需要依赖,所以您需要使用工厂作为目标.
// module.config.php
'view_helpers' => [
'factories' => [
'foobar' => 'My\Something\FooBarHelperFactory'
]
]
Run Code Online (Sandbox Code Playgroud)
目标现在是一个工厂级,我们还没有写.所以继续:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以在任何视图文件中使用ViewHelpervia $this->foobar($args).
每当你依赖于ServiceManager依赖时,你就会陷入糟糕的设计中.您的类将具有未知类型的依赖项,并且它们是隐藏的.每当你的类需要一些外部数据时,通过__construct()直接使它可用,并且不要通过注入来隐藏依赖项ServiceManager.
| 归档时间: |
|
| 查看次数: |
5053 次 |
| 最近记录: |