问题
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