Search code examples
zend-framework2

Show username of logged in user in zf2


I have login and logout system in ZF2. I want to show username of logged in user when he/she is logged in. Screen shot is given below: enter image description here

I have different views like view/provinces/index.phtml, view/districts/index.phtml, etc.

I have layout.phtml in view/layout/layout.phtml, in which I described layout for admin which is for every view. So It is necessary to access username of logged in user in layout.phtml.

I have also corresponding controllers like Controller/ProvincesController.php, Controller/DistrictsController.php etc. I can access username of logged in user in Controller/ProvincesController.php etc by the code:

public function getAuthService()
{
    $this->authservice = $this->getServiceLocator()->get('AuthService'); 
    return $this->authservice;  
}

$username = $this->getAuthService()->getStorage()->read(); 

But I am unable to access value of username of logged in user in layout.phtml.

So if anyone know about it or have simple idea or practice about it, then let me know please.

Module.php:

<?php 

namespace Admin;

use Admin\Model\Profile;
use Admin\Model\ProfileTable;

use Admin\Model\Provinces;
use Admin\Model\ProvincesTable;

use Admin\Model\Districts;
use Admin\Model\DistrictsTable; 

use Admin\Model\User;
use Admin\Model\UserTable;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface; 

use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\Authentication\AuthenticationService;

class Module implements AutoloaderProviderInterface
//class Module
{

public function getConfig()
{
    return include __DIR__ . '/config/module.config.php';
}

public function getServiceConfig()
{
    return array(
        'abstract_factories' => array(),
        'aliases' => array(),

        'factories' => array( 

        // SERVICES
          'AuthService' => function($sm) {
            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
            $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user','username','password', 'MD5(?)');

            $authService = new AuthenticationService();
            $authService->setAdapter($dbTableAuthAdapter);
            return $authService;
          },    

          // DB
          'UserTable' =>  function($sm) {
            $tableGateway = $sm->get('UserTableGateway');
            $table = new UserTable($tableGateway);
            return $table;
          },
          'UserTableGateway' => function ($sm) {
            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
            $resultSetPrototype = new ResultSet();
            $resultSetPrototype->setArrayObjectPrototype(new User());
            return new TableGateway('user', $dbAdapter, null,   
            $resultSetPrototype);
          },

          // FORMS
          'LoginForm' => function ($sm) {
            $form = new \Admin\Form\LoginForm();
            $form->setInputFilter($sm->get('LoginFilter'));
            return $form;
          },


           // FILTERS
          'LoginFilter' => function ($sm) {
            return new \Admin\Form\LoginFilter();
           },


            'Admin\Model\ProvincesTable' =>  function($sm) {
                $tableGateway = $sm->get('ProvincesTableGateway');
                $table = new ProvincesTable($tableGateway);
                return $table;
            },
            'ProvincesTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Provinces());
                return new TableGateway('provinces', $dbAdapter, null, $resultSetPrototype);
            },

            'Admin\Model\DistrictsTable' =>  function($sm) {
                $tableGateway = $sm->get('DistrictsTableGateway');
                $table = new DistrictsTable($tableGateway);
                return $table;
            },
            'DistrictsTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Districts());
                return new TableGateway('districts', $dbAdapter, null, $resultSetPrototype);
            },



        ),

        'invokables' => array(),
        'services' => array(),
        'shared' => array(),

    );
} 

public function getAutoloaderConfig()
{
    return array( 
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
        // if we're in a namespace deeper than one level we need to fix the \ in the path
                __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
            ),
        ),
    );
}

}

Thanks in advance.


Solution

  • The recommend way would be to use identity (https://framework.zend.com/manual/2.4/en/modules/zend.view.helpers.identity.html) view helper. Then in any view model you could use it as follow:

    if ($user = $this->identity()) {
         echo 'Logged in as ' . $this->escapeHtml($user->getUsername());
     } else {
         echo 'Not logged in';
     }
    

    In order to make it work you have to register your authentication service under specific name- Zend\Authentication\AuthenticationService.

    So in your module.config.php file, add to service_manager:

    'service_manager' => array(
        'aliases' => array(
            'Zend\Authentication\AuthenticationService' => 'AuthService', // <--- this line
        ),
        'invokables' => array(
            'AuthService' => 'Your\Authentication\Class',
        ),
    ),
    

    Then you should be able to use identity controller plugin and view helper.

    In your case, Module.php should look like this:

    ...
    public function getServiceConfig()
    {
        return array(
            'abstract_factories' => array(),
            'aliases' => array(
                 'Zend\Authentication\AuthenticationService' => 'AuthService', // <--- this line
             ),
    
            'factories' => array( 
    
            // SERVICES
              'AuthService' => function($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user','username','password', 'MD5(?)');
    
                $authService = new AuthenticationService();
                $authService->setAdapter($dbTableAuthAdapter);
                return $authService;
              },    
    
              // DB
              'UserTable' =>  function($sm) {
                $tableGateway = $sm->get('UserTableGateway');
                $table = new UserTable($tableGateway);
                return $table;
              },
              'UserTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new User());
                return new TableGateway('user', $dbAdapter, null,   
                $resultSetPrototype);
              },
    
              // FORMS
              'LoginForm' => function ($sm) {
                $form = new \Admin\Form\LoginForm();
                $form->setInputFilter($sm->get('LoginFilter'));
                return $form;
              },
    
    
               // FILTERS
              'LoginFilter' => function ($sm) {
                return new \Admin\Form\LoginFilter();
               },
    
    
                'Admin\Model\ProvincesTable' =>  function($sm) {
                    $tableGateway = $sm->get('ProvincesTableGateway');
                    $table = new ProvincesTable($tableGateway);
                    return $table;
                },
                'ProvincesTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Provinces());
                    return new TableGateway('provinces', $dbAdapter, null, $resultSetPrototype);
                },
    
                'Admin\Model\DistrictsTable' =>  function($sm) {
                    $tableGateway = $sm->get('DistrictsTableGateway');
                    $table = new DistrictsTable($tableGateway);
                    return $table;
                },
                'DistrictsTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Districts());
                    return new TableGateway('districts', $dbAdapter, null, $resultSetPrototype);
                },
    
    
    
            ),
    
            'invokables' => array(),
            'services' => array(),
            'shared' => array(),
    
        );
    } 
    ...
    

    Then in your layout or any other .phtml file:

    layout.phtml
    ...
    <?php if ($this->identity()): ?>
    <p>Welcome, <?php echo $this->identity()->getUsername(); ?></p>
    <?php endif; ?>