0

我有一个自定义身份验证服务,在 ZF2 中我按如下方式访问它:

Application/view/layout/layout.phtml

$authenticationService = $this->getHelperPluginManager()
    ->getServiceLocator()
    ->get('AuthenticationService');
$currentIdentity = $authenticationService->getIdentity();

现在Zend\ServiceManager#getServiceLocator()已弃用。

如何在 ZF3 的视图脚本(或在这种情况下为布局中的具体)中获得可用的服务?

4

2 回答 2

3

为此,已经有Identity View Helper

正如文件所说

// Use it any .phtml file
// return user array you set in AuthenticationService or null
$user = $this->identity(); 
于 2017-06-24T18:22:36.170 回答
1

解决方案是在以下位置分配一个全局视图变量onBootstrap(...)

namespace Application;
use ...
class Module
{

    public function onBootstrap(MvcEvent $e)
    {
        ...
        $serviceManager = $e->getApplication()->getServiceManager();
        $viewModel = $e->getApplication()->getMvcEvent()->getViewModel();
        $viewModel->authenticationService = $serviceManager->get('AuthenticationService');
    }
    ...
}

另一个(也许是更好/更清洁的)解决方案是使用ViewHelper. 另请参见此处

于 2017-06-24T10:48:13.810 回答