0

我有一個自定義的認證服務,並在ZF2我訪問這個如下:如何從Zend Framework 3中的視圖腳本訪問服務?

Application/view/layout/layout.phtml

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

現在Zend\ServiceManager#getServiceLocator()已被棄用。

如何在ZF3中的視圖腳本(或在這種情況下在佈局中具體)獲得服務?

回答

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。另見here

3

爲此已經有Identity View Helper

由於文檔說

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

我完全同意你的觀點! – unclexo

相關問題