8 use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
9 use Drupal\Core\Messenger\LegacyMessenger;
11 use Symfony\Component\DependencyInjection\ContainerInterface;
14 * Static Service Container wrapper.
16 * Generally, code in Drupal should accept its dependencies via either
17 * constructor injection or setter method injection. However, there are cases,
18 * particularly in legacy procedural code, where that is infeasible. This
19 * class acts as a unified global accessor to arbitrary services within the
20 * system in order to ease the transition from procedural code to injected OO
23 * The container is built by the kernel and passed in to this class which stores
24 * it statically. The container always contains the services from
25 * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
26 * service providers defined in $GLOBALS['conf']['container_service_providers'].
28 * This class exists only to support legacy code that cannot be dependency
29 * injected. If your code needs it, consider refactoring it to be object
30 * oriented, if possible. When this is not possible, for instance in the case of
31 * hook implementations, and your code is more than a few non-reusable lines, it
32 * is recommended to instantiate an object implementing the actual logic.
35 * // Legacy procedural code.
36 * function hook_do_stuff() {
37 * $lock = lock()->acquire('stuff_lock');
41 * // Correct procedural code.
42 * function hook_do_stuff() {
43 * $lock = \Drupal::lock()->acquire('stuff_lock');
47 * // The preferred way: dependency injected code.
48 * function hook_do_stuff() {
49 * // Move the actual implementation to a class and instantiate it.
50 * $instance = new StuffDoingClass(\Drupal::lock());
51 * $instance->doStuff();
53 * // Or, even better, rely on the service container to avoid hard coding a
54 * // specific interface implementation, so that the actual logic can be
55 * // swapped. This might not always make sense, but in general it is a good
57 * \Drupal::service('stuff.doing')->doStuff();
60 * interface StuffDoingInterface {
61 * public function doStuff();
64 * class StuffDoingClass implements StuffDoingInterface {
65 * protected $lockBackend;
67 * public function __construct(LockBackendInterface $lock_backend) {
68 * $this->lockBackend = $lock_backend;
71 * public function doStuff() {
72 * $lock = $this->lockBackend->acquire('stuff_lock');
78 * @see \Drupal\Core\DrupalKernel
83 * The current system version.
85 const VERSION = '8.6.4';
88 * Core API compatibility.
90 const CORE_COMPATIBILITY = '8.x';
93 * Core minimum schema version.
95 const CORE_MINIMUM_SCHEMA_VERSION = 8000;
98 * The currently active container object, or NULL if not initialized yet.
100 * @var \Symfony\Component\DependencyInjection\ContainerInterface|null
102 protected static $container;
105 * Sets a new global container.
107 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
108 * A new container instance to replace the current.
110 public static function setContainer(ContainerInterface $container) {
111 static::$container = $container;
115 * Unsets the global container.
117 public static function unsetContainer() {
118 static::$container = NULL;
122 * Returns the currently active global container.
124 * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
126 * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
128 public static function getContainer() {
129 if (static::$container === NULL) {
130 throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.');
132 return static::$container;
136 * Returns TRUE if the container has been initialized, FALSE otherwise.
140 public static function hasContainer() {
141 return static::$container !== NULL;
145 * Retrieves a service from the container.
147 * Use this method if the desired service is not one of those with a dedicated
148 * accessor method below. If it is listed below, those methods are preferred
149 * as they can return useful type hints.
152 * The ID of the service to retrieve.
155 * The specified service.
157 public static function service($id) {
158 return static::getContainer()->get($id);
162 * Indicates if a service is defined in the container.
165 * The ID of the service to check.
168 * TRUE if the specified service exists, FALSE otherwise.
170 public static function hasService($id) {
171 // Check hasContainer() first in order to always return a Boolean.
172 return static::hasContainer() && static::getContainer()->has($id);
180 public static function root() {
181 return static::getContainer()->get('app.root');
185 * Gets the active install profile.
187 * @return string|null
188 * The name of the active install profile.
190 public static function installProfile() {
191 return static::getContainer()->getParameter('install_profile');
195 * Indicates if there is a currently active request object.
198 * TRUE if there is a currently active request object, FALSE otherwise.
200 public static function hasRequest() {
201 // Check hasContainer() first in order to always return a Boolean.
202 return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL;
206 * Retrieves the currently active request object.
208 * Note: The use of this wrapper in particular is especially discouraged. Most
209 * code should not need to access the request directly. Doing so means it
210 * will only function when handling an HTTP request, and will require special
211 * modification or wrapping when run from a command line tool, from certain
212 * queue processors, or from automated tests.
214 * If code must access the request, it is considerably better to register
215 * an object with the Service Container and give it a setRequest() method
216 * that is configured to run when the service is created. That way, the
217 * correct request object can always be provided by the container and the
218 * service can still be unit tested.
220 * If this method must be used, never save the request object that is
221 * returned. Doing so may lead to inconsistencies as the request object is
222 * volatile and may change at various times, such as during a subrequest.
224 * @return \Symfony\Component\HttpFoundation\Request
225 * The currently active request object.
227 public static function request() {
228 return static::getContainer()->get('request_stack')->getCurrentRequest();
232 * Retrieves the request stack.
234 * @return \Symfony\Component\HttpFoundation\RequestStack
237 public static function requestStack() {
238 return static::getContainer()->get('request_stack');
242 * Retrieves the currently active route match object.
244 * @return \Drupal\Core\Routing\RouteMatchInterface
245 * The currently active route match object.
247 public static function routeMatch() {
248 return static::getContainer()->get('current_route_match');
252 * Gets the current active user.
254 * @return \Drupal\Core\Session\AccountProxyInterface
256 public static function currentUser() {
257 return static::getContainer()->get('current_user');
261 * Retrieves the entity manager service.
263 * @return \Drupal\Core\Entity\EntityManagerInterface
264 * The entity manager service.
266 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
267 * Use \Drupal::entityTypeManager() instead in most cases. If the needed
268 * method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the
269 * deprecated \Drupal\Core\Entity\EntityManager to find the
270 * correct interface or service.
272 public static function entityManager() {
273 return static::getContainer()->get('entity.manager');
277 * Retrieves the entity type manager.
279 * @return \Drupal\Core\Entity\EntityTypeManagerInterface
280 * The entity type manager.
282 public static function entityTypeManager() {
283 return static::getContainer()->get('entity_type.manager');
287 * Returns the current primary database.
289 * @return \Drupal\Core\Database\Connection
290 * The current active database's master connection.
292 public static function database() {
293 return static::getContainer()->get('database');
297 * Returns the requested cache bin.
300 * (optional) The cache bin for which the cache object should be returned,
301 * defaults to 'default'.
303 * @return \Drupal\Core\Cache\CacheBackendInterface
304 * The cache object associated with the specified bin.
308 public static function cache($bin = 'default') {
309 return static::getContainer()->get('cache.' . $bin);
313 * Retrieves the class resolver.
315 * This is to be used in procedural code such as module files to instantiate
316 * an object of a class that implements
317 * \Drupal\Core\DependencyInjection\ContainerInjectionInterface.
319 * One common usecase is to provide a class which contains the actual code
320 * of a hook implementation, without having to create a service.
322 * @param string $class
323 * (optional) A class name to instantiate.
325 * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|object
326 * The class resolver or if $class is provided, a class instance with a
327 * given class definition.
329 * @throws \InvalidArgumentException
330 * If $class does not exist.
332 public static function classResolver($class = NULL) {
334 return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class);
336 return static::getContainer()->get('class_resolver');
340 * Returns an expirable key value store collection.
342 * @param string $collection
343 * The name of the collection holding key and value pairs.
345 * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
346 * An expirable key value store collection.
348 public static function keyValueExpirable($collection) {
349 return static::getContainer()->get('keyvalue.expirable')->get($collection);
353 * Returns the locking layer instance.
355 * @return \Drupal\Core\Lock\LockBackendInterface
359 public static function lock() {
360 return static::getContainer()->get('lock');
364 * Retrieves a configuration object.
366 * This is the main entry point to the configuration API. Calling
367 * @code \Drupal::config('book.admin') @endcode will return a configuration
368 * object in which the book module can store its administrative settings.
370 * @param string $name
371 * The name of the configuration object to retrieve. The name corresponds to
372 * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
373 * object returned will contain the contents of book.admin configuration file.
375 * @return \Drupal\Core\Config\ImmutableConfig
376 * An immutable configuration object.
378 public static function config($name) {
379 return static::getContainer()->get('config.factory')->get($name);
383 * Retrieves the configuration factory.
385 * This is mostly used to change the override settings on the configuration
386 * factory. For example, changing the language, or turning all overrides on
389 * @return \Drupal\Core\Config\ConfigFactoryInterface
390 * The configuration factory service.
392 public static function configFactory() {
393 return static::getContainer()->get('config.factory');
397 * Returns a queue for the given queue name.
399 * The following values can be set in your settings.php file's $settings
400 * array to define which services are used for queues:
401 * - queue_reliable_service_$name: The container service to use for the
402 * reliable queue $name.
403 * - queue_service_$name: The container service to use for the
405 * - queue_default: The container service to use by default for queues
406 * without overrides. This defaults to 'queue.database'.
408 * @param string $name
409 * The name of the queue to work with.
410 * @param bool $reliable
411 * (optional) TRUE if the ordering of items and guaranteeing every item
412 * executes at least once is important, FALSE if scalability is the main
413 * concern. Defaults to FALSE.
415 * @return \Drupal\Core\Queue\QueueInterface
416 * The queue object for a given name.
418 public static function queue($name, $reliable = FALSE) {
419 return static::getContainer()->get('queue')->get($name, $reliable);
423 * Returns a key/value storage collection.
425 * @param string $collection
426 * Name of the key/value collection to return.
428 * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
430 public static function keyValue($collection) {
431 return static::getContainer()->get('keyvalue')->get($collection);
435 * Returns the state storage service.
437 * Use this to store machine-generated data, local to a specific environment
438 * that does not need deploying and does not need human editing; for example,
439 * the last time cron was run. Data which needs to be edited by humans and
440 * needs to be the same across development, production, etc. environments
441 * (for example, the system maintenance message) should use \Drupal::config() instead.
443 * @return \Drupal\Core\State\StateInterface
445 public static function state() {
446 return static::getContainer()->get('state');
450 * Returns the default http client.
452 * @return \GuzzleHttp\Client
453 * A guzzle http client instance.
455 public static function httpClient() {
456 return static::getContainer()->get('http_client');
460 * Returns the entity query object for this entity type.
462 * @param string $entity_type
463 * The entity type (for example, node) for which the query object should be
465 * @param string $conjunction
466 * (optional) Either 'AND' if all conditions in the query need to apply, or
467 * 'OR' if any of them is sufficient. Defaults to 'AND'.
469 * @return \Drupal\Core\Entity\Query\QueryInterface
470 * The query object that can query the given entity type.
472 public static function entityQuery($entity_type, $conjunction = 'AND') {
473 return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction);
477 * Returns the entity query aggregate object for this entity type.
479 * @param string $entity_type
480 * The entity type (for example, node) for which the query object should be
482 * @param string $conjunction
483 * (optional) Either 'AND' if all conditions in the query need to apply, or
484 * 'OR' if any of them is sufficient. Defaults to 'AND'.
486 * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
487 * The query object that can query the given entity type.
489 public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
490 return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction);
494 * Returns the flood instance.
496 * @return \Drupal\Core\Flood\FloodInterface
498 public static function flood() {
499 return static::getContainer()->get('flood');
503 * Returns the module handler.
505 * @return \Drupal\Core\Extension\ModuleHandlerInterface
507 public static function moduleHandler() {
508 return static::getContainer()->get('module_handler');
512 * Returns the typed data manager service.
514 * Use the typed data manager service for creating typed data objects.
516 * @return \Drupal\Core\TypedData\TypedDataManagerInterface
517 * The typed data manager.
519 * @see \Drupal\Core\TypedData\TypedDataManager::create()
521 public static function typedDataManager() {
522 return static::getContainer()->get('typed_data_manager');
526 * Returns the token service.
528 * @return \Drupal\Core\Utility\Token
531 public static function token() {
532 return static::getContainer()->get('token');
536 * Returns the url generator service.
538 * @return \Drupal\Core\Routing\UrlGeneratorInterface
539 * The url generator service.
541 public static function urlGenerator() {
542 return static::getContainer()->get('url_generator');
546 * Generates a URL string for a specific route based on the given parameters.
548 * This method is a convenience wrapper for generating URL strings for URLs
549 * that have Drupal routes (that is, most pages generated by Drupal) using
550 * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
551 * detailed documentation. For non-routed local URIs relative to
552 * the base path (like robots.txt) use Url::fromUri()->toString() with the
555 * @param string $route_name
556 * The name of the route.
557 * @param array $route_parameters
558 * (optional) An associative array of parameter names and values.
559 * @param array $options
560 * (optional) An associative array of additional options.
561 * @param bool $collect_bubbleable_metadata
562 * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
563 * associated bubbleable metadata are returned.
565 * @return string|\Drupal\Core\GeneratedUrl
566 * A string containing a URL to the given path.
567 * When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
568 * returned, containing the generated URL plus bubbleable metadata.
570 * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
571 * @see \Drupal\Core\Url
572 * @see \Drupal\Core\Url::fromRoute()
573 * @see \Drupal\Core\Url::fromUri()
575 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0.
576 * Instead create a \Drupal\Core\Url object directly, for example using
579 public static function url($route_name, $route_parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
580 return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);
584 * Returns the link generator service.
586 * @return \Drupal\Core\Utility\LinkGeneratorInterface
588 public static function linkGenerator() {
589 return static::getContainer()->get('link_generator');
593 * Renders a link with a given link text and Url object.
595 * This method is a convenience wrapper for the link generator service's
598 * @param string $text
599 * The link text for the anchor tag.
600 * @param \Drupal\Core\Url $url
601 * The URL object used for the link.
603 * @return \Drupal\Core\GeneratedLink
604 * A GeneratedLink object containing a link to the given route and
605 * parameters and bubbleable metadata.
607 * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
608 * @see \Drupal\Core\Url
610 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
611 * Use \Drupal\Core\Link instead.
614 * $link = Link::fromTextAndUrl($text, $url);
617 public static function l($text, Url $url) {
618 return static::getContainer()->get('link_generator')->generate($text, $url);
622 * Returns the string translation service.
624 * @return \Drupal\Core\StringTranslation\TranslationManager
625 * The string translation manager.
627 public static function translation() {
628 return static::getContainer()->get('string_translation');
632 * Returns the language manager service.
634 * @return \Drupal\Core\Language\LanguageManagerInterface
635 * The language manager.
637 public static function languageManager() {
638 return static::getContainer()->get('language_manager');
642 * Returns the CSRF token manager service.
644 * The generated token is based on the session ID of the current user. Normally,
645 * anonymous users do not have a session, so the generated token will be
646 * different on every page request. To generate a token for users without a
647 * session, manually start a session prior to calling this function.
649 * @return \Drupal\Core\Access\CsrfTokenGenerator
650 * The CSRF token manager.
652 * @see \Drupal\Core\Session\SessionManager::start()
654 public static function csrfToken() {
655 return static::getContainer()->get('csrf_token');
659 * Returns the transliteration service.
661 * @return \Drupal\Core\Transliteration\PhpTransliteration
662 * The transliteration manager.
664 public static function transliteration() {
665 return static::getContainer()->get('transliteration');
669 * Returns the form builder service.
671 * @return \Drupal\Core\Form\FormBuilderInterface
674 public static function formBuilder() {
675 return static::getContainer()->get('form_builder');
679 * Gets the theme service.
681 * @return \Drupal\Core\Theme\ThemeManagerInterface
683 public static function theme() {
684 return static::getContainer()->get('theme.manager');
688 * Gets the syncing state.
691 * Returns TRUE is syncing flag set.
693 public static function isConfigSyncing() {
694 return static::getContainer()->get('config.installer')->isSyncing();
698 * Returns a channel logger object.
700 * @param string $channel
701 * The name of the channel. Can be any string, but the general practice is
702 * to use the name of the subsystem calling this.
704 * @return \Psr\Log\LoggerInterface
705 * The logger for this channel.
707 public static function logger($channel) {
708 return static::getContainer()->get('logger.factory')->get($channel);
712 * Returns the menu tree.
714 * @return \Drupal\Core\Menu\MenuLinkTreeInterface
717 public static function menuTree() {
718 return static::getContainer()->get('menu.link_tree');
722 * Returns the path validator.
724 * @return \Drupal\Core\Path\PathValidatorInterface
726 public static function pathValidator() {
727 return static::getContainer()->get('path.validator');
731 * Returns the access manager service.
733 * @return \Drupal\Core\Access\AccessManagerInterface
734 * The access manager service.
736 public static function accessManager() {
737 return static::getContainer()->get('access_manager');
741 * Returns the redirect destination helper.
743 * @return \Drupal\Core\Routing\RedirectDestinationInterface
744 * The redirect destination helper.
746 public static function destination() {
747 return static::getContainer()->get('redirect.destination');
751 * Returns the entity definition update manager.
753 * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
754 * The entity definition update manager.
756 public static function entityDefinitionUpdateManager() {
757 return static::getContainer()->get('entity.definition_update_manager');
761 * Returns the time service.
763 * @return \Drupal\Component\Datetime\TimeInterface
766 public static function time() {
767 return static::getContainer()->get('datetime.time');
771 * Returns the messenger.
773 * @return \Drupal\Core\Messenger\MessengerInterface
776 public static function messenger() {
777 // @todo Replace with service once LegacyMessenger is removed in 9.0.0.
778 // @see https://www.drupal.org/node/2928994
779 return new LegacyMessenger();