ZendFramework 2 AuthService available in ViewFile

主宰稳场 提交于 2019-12-24 09:39:07

问题


I wanted to get something like this (this is from controller)

$authService = $this->serviceLocator->get('auth_service');
if ($authService->hasIdentity()) {
    [...]
} else {
    [...]
}

in the view file (*.phtml) co i can display login or logout link...


回答1:


There's an identity() view helper already available in the framework, to use it you need to map your auth service instance to Zend\Authentication\AuthenticationService, which you can do by aliasing it to your auth_service in your module.config.php, eg..

<?php
return array(
    //..
    'service_manager' => array(
        'aliases' => array(
            'Zend\Authentication\AuthenticationService' => 'auth_service',
        ),
    ),
    // ..
);

The helper has no parameters, it simply returns the identity or null, so for your example of testing if user is authenticated, in your view, you'd use ...

<?php
if ($this->identity()) : ?>
    Logged In User
<?php else : ?>
    Guest
<?php endif; ?>



回答2:


You need to create a custom View Helper to expose methods from the AuthService to the view. For an example, take a look at the way ZfcUser created their view helper. I would point out, however, that they're injecting the AuthenticationService into the view helper. This was done through a configuration closure in the Module.php file.



来源:https://stackoverflow.com/questions/17012622/zendframework-2-authservice-available-in-viewfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!