CakePHP 3.x - AuthComponent::user() in View

不问归期 提交于 2019-12-04 04:21:55

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 } ?>
mario741

In View:

$this->request->session()->read('Auth.User.username');

In Controller

$this->Auth->user('username');
mark

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
}

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.

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