0

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?

automatix
  • 14,018
  • 26
  • 105
  • 230

2 Answers2

3

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(); 
tasmaniski
  • 4,767
  • 3
  • 33
  • 65
1

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.

automatix
  • 14,018
  • 26
  • 105
  • 230