1
votes

Using the AuthComponent in CakePHP 3, you can access the currently logged in user in a Controller using $this->Auth->user(). However, this method returns only an array, not a User Entity.

In many places, I have to work with the User Entity of the logged in user, but have to query the UsersTable manually after getting the id from the AuthComponent, which seems quite silly, as the AuthComponent fetches a hydrated User Entity anyway and flattens it to an array. So the User Entity is fetched twice.

Is there a way to get the hydrated User Entity from the AuthComponent instead of an array?

$authUser = $this->Auth->user('id');
if($authUser !== null) {
    $authUser = $users->get($authUser);
}
1
If nobody has a proper solution for you, a workaround might be to create an entity from the array, same as if you were about to save form data. - Greg Schmidt

1 Answers

1
votes

The main reason entities are not stored in the sessions is because there is no guarantee that the auth data is an actual database user. For example, you may be authenticating some credentials from an external system, such as a single sign on in a remote server.

Another reason is that user info can be expected to change from request to request and doing a db lookup on each request is less than ideal.

Finally, people could think that by changing the data in the session entity they would be modifying the user (or modifying the data in the table would refresh the session).

I would suggest just converting your array data to an entity using new User($data) whenever you need an entity.