Cakephp 3.7.x如何检索用户数据?使用身份验证组件

时间:2019-01-07 11:00:02

标签: authentication cakephp cakephp-3.7

我正在使用带有身份验证组件的cakephp 3.7.2

$user = $this->Authentication->getIdentity();

打印:

object(Authentication\Identity) {

'config' => [
    'fieldMap' => [
        'id' => 'id'
    ]
],
'data' => object(App\Model\Entity\User) {

    'id' => (int) 1,
    'email' => 'aa.aaa@gmail.com',
    ...
 }
}

我尝试过$user->data,但是它不起作用。

如何打印用户数据?

Authentication Component

3 个答案:

答案 0 :(得分:0)

根据身份验证组件文档

  

身份对象由服务返回,并在   请求。该对象提供了一个方法getIdentifier(),可以是   调用以获取当前登录标识的ID。

您可以按照以下方式相应地使用它来获取用户数据:

 // Service
   $identity =  $authenticationService
        ->getIdentity()
        ->getIdentifier()

    // Component
    $identity = $this->Authentication
        ->getIdentity()
        ->getIdentifier();

    // Request
   $identity = $this->request
        ->getAttribute('identity')
        ->getIdentifier();
  

标识对象提供ArrayAccess以及get()方法   访问数据。强烈建议使用get()方法   数组访问,因为get方法知道字段映射。

例如要通过身份访问电子邮件和用户名,您可以使用以下代码。

 $identity->get('email'); // to access email 
    $identity->get('username'); // to access username

参考链接:Authentication -> Docs -> Identity Object

希望这会有所帮助。

答案 1 :(得分:0)

So I have figured it out.

In User Entity class

Add use Authentication\IdentityInterface;

and then implement the IdentityInterface.

class User extends Entity implements IdentityInterface
{

blablabla...
yale yale yale ...

Now you can print:

 $user = $this->Authentication->getIdentity();   
 debug($user->id);

答案 2 :(得分:0)

我在CakePHP 4.xxx中使用AuthComponent。

我可以在以下视图中获取用户数据

$user = $this->getRequest()->getAttribute('identity');

我在http://gotchahosting.com/blog/category/cakephp/4002624

上找到了信息

也许它可以帮助正在CakePHP4中查找有关此信息的人