0
votes

I am new in zend and using zend framework 2.5.1. Using "authservice" i have done login authentication in my project. I am able to fetch login detail by using $this->getAuthService()->getIdentity(); in my controller. But i want to use it in each and every view page (layout). So that i could manage session but i am unable to do this. Moreover i want to display logged in username in layout.phtml(or header.phtml). I want to show logged in user name like "Welcome ABC". So please help me to solve this problem.

2

2 Answers

2
votes

See the Identity view helper for in your view files like: layout.phtml or page specific ones.

Just like the document states:

if ($user = $this->identity()) {
    echo $this->translate('Welcome') . ' ' . $this->escapeHtml($user->getUsername());
} else {
    echo $this->translate('Welcome guest');
}
1
votes

I use a custom view helper to achieve this, passing the Auth service via factory.

My view helper

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\Authentication\AuthenticationService;

class WelcomeUser extends AbstractHelper
{

    private $welcomeUser;

    /**
     *
     * @param AuthenticationService $auth
     */
    public function __construct(AuthenticationService $auth)
    {
        $this->welcomeUser = 'Guest';
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            $this->welcomeUser = $user->getFirstLastName();
        }
    }

    /**
     *
     * @return string
     */
    public function __invoke()
    {
        return $this->welcomeUser;
    }

}

And it's factory

namespace Application\View\Helper\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\View\Helper\WelcomeUser;
use Zend\Authentication\AuthenticationService;

class WelcomeUserFactory implements FactoryInterface
{

    /**
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return WelcomeUser
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new WelcomeUser($serviceLocator->getServiceLocator()->get(AuthenticationService::class));
    }

}

Don't forget to register you view helper in module.config.php

'view_helpers' => array(
        'factories' => array(
            'welcomeUser' => 'Application\View\Helper\Service\WelcomeUserFactory',
        ),
    ),

Finally in your layout.phtml use <?php echo $this->welcomeUser(); ?>

I hope this point you in the right direction.