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

Cakephp 3.7.x How to retrieve user data? using Authentication component

我正在使用带有身份验证组件的 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

根据身份验证组件文档

The identity object is returned by the service and made available in the request. The object provides a method getIdentifier() that can be called to get the id of the current log in identity.

您可以如下所示相应地使用它来获取用户数据:

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

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

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

The identity object provides ArrayAccess but as well a get() method to access data. It is strongly recommended to use the get() method over array access because the get method is aware of the field mapping.

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

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

参考link:Authentication -> Docs -> Identity Object

希望这会有所帮助。

所以我想通了。

在用户实体中 class

添加use Authentication\IdentityInterface;

然后实现IdentityInterface。

class User extends Entity implements IdentityInterface
{

blablabla...
yale yale yale ...

现在您可以打印:

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

我在 CakePHP 中使用 AuthComponent 4.xxx。

我可以获取用户数据,即在具有

的视图中
$user = $this->getRequest()->getAttribute('identity');

我找到了以下信息:http://gotchahosting.com/blog/category/cakephp/4002624

也许它可以帮助正在 CakePHP4 中寻找相关信息的人