[英]How to get the current user object in Drupal 8?
我精通 Drupal 7,我从global $user
获取当前用户对象,但如何在 Drupal 8 中获取它?
One liner way to get a full drupal user object for the current active user :为当前活动用户获取完整drupal 用户对象的一种线性方法:
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
Why not just Drupal::currentUser()
?为什么不只是
Drupal::currentUser()
? Because most of the time it won't be sufficient as you'll need a fully loaded user object while it's not :因为大多数时候它是不够的,因为您需要一个完全加载的用户对象,而它不是:
\\Drupal::currentUser()
returns an AccountProxyInterface
. \\Drupal::currentUser()
返回一个AccountProxyInterface
。\\Drupal\\user\\Entity\\User::load()
actually returns a user entity object . \\Drupal\\user\\Entity\\User::load()
实际上返回一个用户实体对象。请使用以下代码获取 Drupal 8 中的当前用户对象: $user = \\Drupal::currentUser();
$user = \Drupal::currentUser();
要获取当前用户 ID,您可以使用:
$user = User::load(\Drupal::currentUser()->id());
According to entity api , we should not use User::load.根据entity api ,我们不应该使用 User::load。 Instead, use entityTypeManager like so :
相反,像这样使用 entityTypeManager :
$user_id = \Drupal::currentUser()->id();
$user_entity = \Drupal::entityTypeManager()->getStorage('user')->load($user_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.