简体   繁体   中英

How to access services from a view script in Zend Framework 3?

I have a custom authentication service and in ZF2 I accessed this as follows:

Application/view/layout/layout.phtml

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

Now the Zend\\ServiceManager#getServiceLocator() is deprecated.

How to get a service available in a view script (or concrete in this case in the layout) in ZF3?

For this purpose there is already Identity View Helper

As documentation says

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

The solution is to assign a global view variable in the 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');
    }
    ...
}

Another (perhaps an even better/cleaner) solution is to use a ViewHelper . See also here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM