问题
In CakePHP 2.x you could do
AuthComponent::user()
in View to get data from Auth component. In CakePHP 3.0beta3 it throws:
"Error: Class 'AuthComponent' not found"
Is there a simple way to get data from AuthComponent in View?
回答1:
Cake 3.5
In AppController:
public function beforeRender(Event $event) {
....
$this->set('Auth', $this->Auth);
}
In .ctp template:
<?php if (!$Auth->user()) { ?>
<a class="login" href="<?php echo $this->Url->build($Auth->getConfig('loginAction')); ?>">Login</a>
<?php } else { ?>
<div class="name"><?php echo h($Auth->user('name')); ?></div>
<?php } ?>
回答2:
In View:
$this->request->session()->read('Auth.User.username');
In Controller
$this->Auth->user('username');
回答3:
You should have never used the AuthComponent in views in the first place. It is better to either pass down the data from the controller to the view and access that, or better yet, use a AuthHelper to wrapper-access it easily (by reading from the session there for example).
An example would be AuthUser
(
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/AuthUserHelper.php ):
$this->AuthUser->id();
$this->AuthUser->user('username');
etc
The helper way doesn't require additional use statements in your view ctps and keeps them lean. It also prevents notices when trying to access undefined indexed automatically.
if ($this->AuthUser->user('foobarbaz')) { // no error thrown even if it never existed
}
回答4:
The AuthComponent is deprecated as of 4.0.0 and will be replaced by the authorization and authentication plugins.
Authentication plugin has built in View Helper.
来源:https://stackoverflow.com/questions/27573134/cakephp-3-x-authcomponentuser-in-view