我需要编写一个 View 助手来获取服务并使用它做一些事情。我成功地实现了 View 助手以访问服务定位器。问题是在调用 __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();
}
}
模型代码片段:
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;
}
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',
),
),
从任何 View 调用 View 助手时,我得到以下信息:
Zend\View\HelperPluginManager::get was unable to fetch or create an instance for Application\Auth
奇怪的是应用程序运行正常(即该服务正被应用程序的其他部分正常使用)。
编辑:
我做了一些研究,我认为我可以通过 View 助手中的服务管理器访问的唯一服务是在 module.config.php 的“view_manager”部分中注册的服务。有没有人知道如何访问其他服务?
最佳答案
$this->getServiceLocator()
in view helper 只能获取你需要使用的其他 View helpers $this->getServiceLocator()->getServiceLocator()
获取应用服务
关于php - View Helper 中的 Zend Framework 2 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20941432/