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

In CakePHP 2.x you can do

AuthComponent::user() 

in the view to get data from the Auth component. In CakePHP 3.0beta3, it throws:

  "Error: Class 'AuthComponent' not found" 

Is there an easy way to get data from AuthComponent in a view?

+7
cakephp
source share
4 answers

Cake 3.5

In AppController:

 public function beforeRender(Event $event) { .... $this->set('Auth', $this->Auth); } 

In the .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 } ?> 
+4
source share

In view:

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

In the controller

 $this->Auth->user('username'); 
+17
source share

First of all, you should never use AuthComponent. It’s better to either pass the data from the controller to the view, or access it, or better yet, use AuthHelper to access the wrapper β€” it's easy to get it (for example, by reading it from the session).

Example: AuthUser ( https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/AuthUserHelper.php ):

 $this->AuthUser->id(); $this->AuthUser->user('username'); 

etc.

The helper path does not require additional use statements in your ctps view and supports them. It also prevents notifications when trying to automatically access undefined.

 if ($this->AuthUser->user('foobarbaz')) { // no error thrown even if it never existed } 
+9
source share

AuthComponent is deprecated since version 4.0.0 and will be replaced by authorization and authentication authentication plugins.

The authentication plugin has a built-in View Helper .

0
source share

All Articles