phpzend-framework2zend-authservice-locator

How to use Zend Auth to make values globally available in each action & layout.phtml


I have implemented Zend Auth by creating a getServiceConfig()-like AuthenticationService Object in Module.php:

'AuthService' => function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'tblUSRUsers', 'Email', 'Password', "MD5(?)");

                    $authService = new AuthenticationService();
                    $authService->setAdapter($dbTableAuthAdapter);
                    $authService->setStorage($sm->get('Application\Model\MyAuthStorage'));

                    return $authService;
                },

In the controller action, I am getting this object by

$this->getServiceLocator()
                    ->get('AuthService');

For authentication I obtain the values using

$authservice    = $this->getServiceLocator()->get('AuthService');
$arrUserDetails = $authservice->getIdentity();

Its working fine, these values are available.

But the problem is that ServiceLocator is not available in the Controller constructor so can't write the above code there. Writing this code in each and every action doesn't seem to be a good practice. Could anyone help out with this?


Solution

  • Possible solution would be to have a route event handler, where you set user credentials:

    class Module
    {
        public function onBootstrap(MvcEvent $e)
        {
            $eventManager = $e->getApplication()
                ->getEventManager ();
    
            $eventManager->attach (
                MvcEvent::EVENT_ROUTE,
                function  (MvcEvent $e)
                {
                    $auth = $e->getApplication()
                              ->getServiceManager()
                              ->get('AuthService');
    
                    $e->setParam('userinfo', $auth->getUserInfo());
                    // update 
                    $layout = $e->getViewModel();
                    $layout->userinfo = $auth->getUserInfo();           
           });
        }
    

    and then access then in the controller like this:

    class IndexController extends AbstractActionController
    {
        public function indexAction ()
        {
            $this->getEvent()->getParam('userinfo');