如果用户已插入,我如何显示或隐藏登录/注销链接。是否应该直接在视图中完成?
在我的onDispatch中,我看到它正在使用$this->getAdminAuthService()->hasIdentity()
来检查用户是否已被插入。
如何在这样的视图中使用它?
if($this->getAdminAuthService()->hasIdentity()){
echo "<a href="#">login</a>";
}
else {
echo "<a href="#">Logout</a>"
}
答案 0 :(得分:1)
在你的控制器中试试这个:
public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
$header = new ViewModel(array('login'=>$this->getAdminAuthService()->hasIdentity()));
$header->setTemplate('layout/header');
$this->layout()->addChild($header, 'header');
}
然后:
//layout/header.phtml
if($this->login){
echo "<a href="#">login</a>";
} else {
echo "<a href="#">Logout</a>"
}
答案 1 :(得分:1)
对于此
,view helper可能是更独立的解决方案namespace MyModule\View\Helper;
use Zend\View\Helper\AbstractHelper;
use MyModule\Service\AuthService;
class IsAuthenticated extends AbstractHelper
{
protected $authService;
public function __construct(AuthService $authService) {
$this->authService = $authService;
}
public function __invoke()
{
return $this->authService->hasIdentity();
}
}
在module.php
public function getViewHelperConfig()
{
return array(
'factories' => array(
'IsAuthenticated' => factory($sl) {
$authService = $sl->getServiceLocator()->get('AuthService');
return new View\Helper\IsAuthenticated($authService);
},
),
);
}
然后您可以在视图或布局中使用它 - 可能使用视图部分
if ($this->isAuthenticated()) {
// render the login/logout
$this->partial('some/view/file', array('foo', 'bar'));
}
可以将插件扩展为代理其他AuthService
方法。但是我希望这个简短的例子说明如何去做。
答案 2 :(得分:1)
我不知道您使用的是哪个版本的ZF2,但2.2.x附带了一个视图帮助程序,用于从AuthenticationService开箱即用地检查用户的身份。
$this->identity();