This question depends on where you are trying to access this information.
Dependency injection is the ideal way to call drupal services.
Often what you can do is go to core ([webroot]/core/lib/core), and look at core.services.yml. Tons of services are used in this file, making it a great reference point.
For instance you want the current user, so search for say 'user' and look for '@[service-name] definitions. In this case you will find a '@current_user'.
This means a service exists with that name. That service also happens to be defined in this file. Further down you will find the 'current_user:' service definition.
current_user:
class: Drupal\Core\Session\AccountProxy
arguments: ['@event_dispatcher']
Within that you can see what class it calls, so when you inject this service, or call for the current user via \Drupal::currentUser()
, this is the class it is calling.
You can then open up that class to see what is available for use.
If you are writing a custom module, you add a [module_name].services.yml file and define your modules service name, then inject the @current_user service.
Which means adding your @ service values to the arguments array of comma separated values.
For instance:
services:
commerce_custom_shipping_carts:
class: '\Drupal\commerce_custom_shipping_carts\EventSubscriber\CommerceCustomShippingCartsEventSubscriber'
arguments: ['@messenger', '@string_translation', '@current_user']
tags:
- { name: 'event_subscriber' }
Then within your class constructor, pass in the service:
* Messenger Interface.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* String Translation Interface.
*
* @var \Drupal\Core\StringTranslation\TranslationInterface
*/
protected $stringTranslation;
/**
* Current user session.
*
* @var \Drupal\Core\Session\AccountProxy
*/
protected $currentUserSession;
/**
* Constructs a new CartEventSubscriber object.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
* @param \Drupal\Core\Session\AccountProxy $currentUserSession
* The current user session.
*/
public function __construct(MessengerInterface $messenger, TranslationInterface $string_translation, AccountProxy $currentUserSession) {
$this->messenger = $messenger;
$this->stringTranslation = $stringTranslation;
$this->currentUserSession = $currentUserSession;
}
Then you can use anything in the class with:
$this->currentUserSession->[method_name]([method_parameters]);
\Drupal\user\Entity\User::load($userCurrent->id());
with a` before the
Drupal` namespace. Otehriwse it is put in the current namespace and leads to an exception.