CakePHP 3.x - View中的AuthComponent :: user()

wil*_*art 7 cakephp cakephp-3.0

在CakePHP 2.x中你可以做到

 AuthComponent::user()
Run Code Online (Sandbox Code Playgroud)

在视图中从Auth组件获取数据.在CakePHP 3.0beta3中,它抛出:

 "Error: Class 'AuthComponent' not found"
Run Code Online (Sandbox Code Playgroud)

是否有一种从View中的AuthComponent获取数据的简单方法?

小智 17

在视图中:

$this->request->session()->read('Auth.User.username');
Run Code Online (Sandbox Code Playgroud)

在控制器中

$this->Auth->user('username');
Run Code Online (Sandbox Code Playgroud)


mar*_*ark 9

您应该从未在视图中使用过AuthComponent.最好是将数据从控制器传递到视图并访问它,或者更好的是,使用AuthHelper轻松地对其进行包装访问(例如,通过从那里的会话读取).

一个例子是AuthUser( https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/AuthUserHelper.php):

$this->AuthUser->id();
$this->AuthUser->user('username');
Run Code Online (Sandbox Code Playgroud)

等等

帮助方式在视图ctps中不需要额外的使用语句,并使它们保持精简.它还会在尝试自动访问未定义索引时阻止通知.

if ($this->AuthUser->user('foobarbaz')) { // no error thrown even if it never existed
}
Run Code Online (Sandbox Code Playgroud)

  • 没错,我已经看到这个功能不再是静态的了.文档似乎还没有更新.我替换`AuthComponent :: user('```$ this-> request-> Session() - > read('Auth.User .`在所有视图文件中再次使用它. (2认同)

And*_*eyP 5

蛋糕 3.5

AppController 中

public function beforeRender(Event $event) {
    ....

    $this->set('Auth', $this->Auth);
}
Run Code Online (Sandbox Code Playgroud)

.ctp模板中:

<?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 } ?>
Run Code Online (Sandbox Code Playgroud)