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

628 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

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();