【问题标题】:How to access services from a view script in Zend Framework 3?如何从 Zend Framework 3 中的视图脚本访问服务?
【发布时间】:2017-06-24 10:33:17
【问题描述】:

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

Application/view/layout/layout.phtml

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

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

如何在 ZF3 中的视图脚本(或本例中的布局中的具体)中获取服务?

【问题讨论】:

    标签: migration service-locator zend-view zend-framework3 zend-servicemanager


    【解决方案1】:

    为此已经有Identity View Helper

    如文档所述

    // Use it any .phtml file
    // return user array you set in AuthenticationService or null
    $user = $this->identity(); 
    

    【讨论】:

    • 我完全同意你的看法!
    【解决方案2】:

    解决方法是在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。另见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 2012-04-08
      • 2015-12-20
      相关资源
      最近更新 更多