migrationservice-locatorzend-viewzend-framework3zend-servicemanager

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?


Solution

  • 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.