raf*_*ame 4 php zend-view zend-framework2
我需要编写一个视图助手来获取服务并使用它做一些事情.我成功实现了视图助手,可以访问服务定位器.问题是,当调用__invoke方法时,无法通过服务定位器找到我想要获取的服务.
视图助手代码:
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper,
Zend\ServiceManager\ServiceLocatorAwareInterface,
Application\Model;
class LoggedCustomer extends AbstractHelper implements ServiceLocatorAwareInterface
{
use \Zend\ServiceManager\ServiceLocatorAwareTrait;
public function __invoke()
{
$model = new Model\Customer($this->getServiceLocator());
return $model->getCurrent();
}
}
Run Code Online (Sandbox Code Playgroud)
模型代码的片段:
namespace Application\Model;
use Application\Entity,
Andreatta\Model\Base as Base;
class Customer extends Base
{
/**
*
* @return Zend\Authentication\AuthenticationService
*/
public function getAuthService()
{
$serviceLocator = $this->getServiceLocator();
return $serviceLocator->get('Application\Auth');
}
/**
*
* @return Zend\Authentication\Adapter\AdapterInterface
*/
protected function getAuthAdapter()
{
return $this->getAuthService()->getAdapter();
}
public function getCurrent()
{
$authService = $this->getAuthService();
if ($authService->hasIdentity())
return $authService->getIdentity();
return null;
}
Run Code Online (Sandbox Code Playgroud)
module.config.php的片段:
'service_manager' => array
(
'factories' => array
(
'Application\Auth' => function($sm)
{
$authService = $sm->get('doctrine.authenticationservice.application');
$authService->setStorage( new \Zend\Authentication\Storage\Session('Application\Auth'));
return $authService;
},
),
),
'view_helpers' => array
(
'invokables' => array
(
'loggedCustomer' => 'Application\View\Helper\LoggedCustomer',
),
),
Run Code Online (Sandbox Code Playgroud)
从任何视图调用视图助手时,我得到以下内容:
Zend\View\HelperPluginManager::get was unable to fetch or create an instance for Application\Auth
Run Code Online (Sandbox Code Playgroud)
奇怪的是应用程序正常运行(即该服务通常由应用程序的其他部分使用).
编辑:
我做了一些研究,我认为我可以通过视图助手内部的服务管理器访问的唯一服务是在module.config.php的'view_manager'部分中注册的服务.有没有人知道如何访问其他服务?
Exl*_*ord 13
$this->getServiceLocator()在视图中,帮助程序只能获取您需要$this->getServiceLocator()->getServiceLocator()用于获取应用程序服务的其他视图帮助程序
小智 7
@rafaame:我找到了一种在视图Helper中访问服务定位器的简单方法
我们只是使用:
$this->getView()->getHelperPluginManager()->getServiceLocator();
Run Code Online (Sandbox Code Playgroud)
获取服务定位器示例视图帮助器:
namespace Tmcore\View\Helper;
use Zend\View\Helper\AbstractHelper;
class Resource extends AbstractHelper
{
public function adminResource()
{
$sm = $this->getView()->getHelperPluginManager()->getServiceLocator();
$adminConfig = $sm->get('ModuleManager')->loadModule('admin')->getConfig();
return $adminConfig;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13017 次 |
| 最近记录: |