Since you are using a getSubscribedEvents()
static method, I get you are implementing an event subscriber. In this case, you don't access \Drupal::currentUser()
(and any static method returning a service that \Drupal
exposes) in that method since it would be getting called too early, when Drupal has not yet initialized the dependency container.
That static method is supposed to return a static array describing the events to which the module wants to subscribe; the methods used to subscribe to the events will eventually take a different action basing on the user currently logged-in, and the user permissions that user account has.
Event subscribers are services, and as such they get their dependency injected. Instead of using \Drupal::currentUser()
, you define @current_user as one of the arguments of your service, which is what the authentication_subscriber service does.
class: Drupal\Core\EventSubscriber\AuthenticationSubscriber
arguments:
- '@authentication'
- '@current_user'
tags:
- { name: event_subscriber }
If you look at AuthenticationSubscriber::__construct()
, you will see how it gets the current user object.
public function __construct(AuthenticationProviderInterface $authentication_provider, AccountProxyInterface $account_proxy) {
$this->authenticationProvider = $authentication_provider;
$this->filter = ($authentication_provider instanceof AuthenticationProviderFilterInterface) ? $authentication_provider : NULL;
$this->challengeProvider = ($authentication_provider instanceof AuthenticationProviderChallengeInterface) ? $authentication_provider : NULL;
$this->accountProxy = $account_proxy;
}
In your case, I would use the following code.
mymodule.services.yml
services:
mymodule.eventsubscriber:
class: Drupal\mymodule\EventSubscriber\MyModuleSubscriber
arguments:
- '@current_user'
tags:
- { name: event_subscriber }
src/EventSubscriber/MyModuleSubscriber.php
namespace Drupal\mymodule\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class MymoduleSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
// Return the array describing the events to which you subscribe.
}
public function __construct(AccountProxyInterface $account_proxy) {
$this->accountProxy = $account_proxy;
}
}
Notice that @current_user is an instance of AccountProxyInterface
, so for example, you can check the user has some user permissions with $this->accountProxy->hasPermission()
.
$account = \Drupal::currentUser();
, will give current user object. To get user ID, you can use\Drupal::currentUser()->id();
directly.