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.5.3';
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;
146 * Retrieves a service from the container.
148 * Use this method if the desired service is not one of those with a dedicated
149 * accessor method below. If it is listed below, those methods are preferred
150 * as they can return useful type hints.
153 * The ID of the service to retrieve.
156 * The specified service.
158 public static function service($id) {
159 return static::getContainer()->get($id);
163 * Indicates if a service is defined in the container.
166 * The ID of the service to check.
169 * TRUE if the specified service exists, FALSE otherwise.
171 public static function hasService($id) {
172 // Check hasContainer() first in order to always return a Boolean.
173 return static::hasContainer() && static::getContainer()->has($id);
181 public static function root() {
182 return static::getContainer()->get('app.root');
186 * Gets the active install profile.
188 * @return string|null
189 * The name of the active install profile.
191 public static function installProfile() {
192 return static::getContainer()->getParameter('install_profile');
196 * Indicates if there is a currently active request object.
199 * TRUE if there is a currently active request object, FALSE otherwise.
201 public static function hasRequest() {
202 // Check hasContainer() first in order to always return a Boolean.
203 return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL;
207 * Retrieves the currently active request object.
209 * Note: The use of this wrapper in particular is especially discouraged. Most
210 * code should not need to access the request directly. Doing so means it
211 * will only function when handling an HTTP request, and will require special
212 * modification or wrapping when run from a command line tool, from certain
213 * queue processors, or from automated tests.
215 * If code must access the request, it is considerably better to register
216 * an object with the Service Container and give it a setRequest() method
217 * that is configured to run when the service is created. That way, the
218 * correct request object can always be provided by the container and the
219 * service can still be unit tested.
221 * If this method must be used, never save the request object that is
222 * returned. Doing so may lead to inconsistencies as the request object is
223 * volatile and may change at various times, such as during a subrequest.
225 * @return \Symfony\Component\HttpFoundation\Request
226 * The currently active request object.
228 public static function request() {
229 return static::getContainer()->get('request_stack')->getCurrentRequest();
233 * Retrives the request stack.
235 * @return \Symfony\Component\HttpFoundation\RequestStack
238 public static function requestStack() {
239 return static::getContainer()->get('request_stack');
243 * Retrieves the currently active route match object.
245 * @return \Drupal\Core\Routing\RouteMatchInterface
246 * The currently active route match object.
248 public static function routeMatch() {
249 return static::getContainer()->get('current_route_match');
253 * Gets the current active user.
255 * @return \Drupal\Core\Session\AccountProxyInterface
257 public static function currentUser() {
258 return static::getContainer()->get('current_user');
262 * Retrieves the entity manager service.
264 * @return \Drupal\Core\Entity\EntityManagerInterface
265 * The entity manager service.
267 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
268 * Use \Drupal::entityTypeManager() instead in most cases. If the needed
269 * method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the
270 * deprecated \Drupal\Core\Entity\EntityManager to find the
271 * correct interface or service.
273 public static function entityManager() {
274 return static::getContainer()->get('entity.manager');
278 * Retrieves the entity type manager.
280 * @return \Drupal\Core\Entity\EntityTypeManagerInterface
281 * The entity type manager.
283 public static function entityTypeManager() {
284 return static::getContainer()->get('entity_type.manager');
288 * Returns the current primary database.
290 * @return \Drupal\Core\Database\Connection
291 * The current active database's master connection.
293 public static function database() {
294 return static::getContainer()->get('database');
298 * Returns the requested cache bin.
301 * (optional) The cache bin for which the cache object should be returned,
302 * defaults to 'default'.
304 * @return \Drupal\Core\Cache\CacheBackendInterface
305 * The cache object associated with the specified bin.
309 public static function cache($bin = 'default') {
310 return static::getContainer()->get('cache.' . $bin);
314 * Retrieves the class resolver.
316 * This is to be used in procedural code such as module files to instantiate
317 * an object of a class that implements
318 * \Drupal\Core\DependencyInjection\ContainerInjectionInterface.
320 * One common usecase is to provide a class which contains the actual code
321 * of a hook implementation, without having to create a service.
323 * @return \Drupal\Core\DependencyInjection\ClassResolverInterface
324 * The class resolver.
326 public static function classResolver() {
327 return static::getContainer()->get('class_resolver');
331 * Returns an expirable key value store collection.
333 * @param string $collection
334 * The name of the collection holding key and value pairs.
336 * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
337 * An expirable key value store collection.
339 public static function keyValueExpirable($collection) {
340 return static::getContainer()->get('keyvalue.expirable')->get($collection);
344 * Returns the locking layer instance.
346 * @return \Drupal\Core\Lock\LockBackendInterface
350 public static function lock() {
351 return static::getContainer()->get('lock');
355 * Retrieves a configuration object.
357 * This is the main entry point to the configuration API. Calling
358 * @code \Drupal::config('book.admin') @endcode will return a configuration
359 * object in which the book module can store its administrative settings.
361 * @param string $name
362 * The name of the configuration object to retrieve. The name corresponds to
363 * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
364 * object returned will contain the contents of book.admin configuration file.
366 * @return \Drupal\Core\Config\ImmutableConfig
367 * An immutable configuration object.
369 public static function config($name) {
370 return static::getContainer()->get('config.factory')->get($name);
374 * Retrieves the configuration factory.
376 * This is mostly used to change the override settings on the configuration
377 * factory. For example, changing the language, or turning all overrides on
380 * @return \Drupal\Core\Config\ConfigFactoryInterface
381 * The configuration factory service.
383 public static function configFactory() {
384 return static::getContainer()->get('config.factory');
388 * Returns a queue for the given queue name.
390 * The following values can be set in your settings.php file's $settings
391 * array to define which services are used for queues:
392 * - queue_reliable_service_$name: The container service to use for the
393 * reliable queue $name.
394 * - queue_service_$name: The container service to use for the
396 * - queue_default: The container service to use by default for queues
397 * without overrides. This defaults to 'queue.database'.
399 * @param string $name
400 * The name of the queue to work with.
401 * @param bool $reliable
402 * (optional) TRUE if the ordering of items and guaranteeing every item
403 * executes at least once is important, FALSE if scalability is the main
404 * concern. Defaults to FALSE.
406 * @return \Drupal\Core\Queue\QueueInterface
407 * The queue object for a given name.
409 public static function queue($name, $reliable = FALSE) {
410 return static::getContainer()->get('queue')->get($name, $reliable);
414 * Returns a key/value storage collection.
416 * @param string $collection
417 * Name of the key/value collection to return.
419 * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
421 public static function keyValue($collection) {
422 return static::getContainer()->get('keyvalue')->get($collection);
426 * Returns the state storage service.
428 * Use this to store machine-generated data, local to a specific environment
429 * that does not need deploying and does not need human editing; for example,
430 * the last time cron was run. Data which needs to be edited by humans and
431 * needs to be the same across development, production, etc. environments
432 * (for example, the system maintenance message) should use \Drupal::config() instead.
434 * @return \Drupal\Core\State\StateInterface
436 public static function state() {
437 return static::getContainer()->get('state');
441 * Returns the default http client.
443 * @return \GuzzleHttp\Client
444 * A guzzle http client instance.
446 public static function httpClient() {
447 return static::getContainer()->get('http_client');
451 * Returns the entity query object for this entity type.
453 * @param string $entity_type
454 * The entity type (for example, node) for which the query object should be
456 * @param string $conjunction
457 * (optional) Either 'AND' if all conditions in the query need to apply, or
458 * 'OR' if any of them is sufficient. Defaults to 'AND'.
460 * @return \Drupal\Core\Entity\Query\QueryInterface
461 * The query object that can query the given entity type.
463 public static function entityQuery($entity_type, $conjunction = 'AND') {
464 return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction);
468 * Returns the entity query aggregate object for this entity type.
470 * @param string $entity_type
471 * The entity type (for example, node) for which the query object should be
473 * @param string $conjunction
474 * (optional) Either 'AND' if all conditions in the query need to apply, or
475 * 'OR' if any of them is sufficient. Defaults to 'AND'.
477 * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
478 * The query object that can query the given entity type.
480 public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
481 return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction);
485 * Returns the flood instance.
487 * @return \Drupal\Core\Flood\FloodInterface
489 public static function flood() {
490 return static::getContainer()->get('flood');
494 * Returns the module handler.
496 * @return \Drupal\Core\Extension\ModuleHandlerInterface
498 public static function moduleHandler() {
499 return static::getContainer()->get('module_handler');
503 * Returns the typed data manager service.
505 * Use the typed data manager service for creating typed data objects.
507 * @return \Drupal\Core\TypedData\TypedDataManagerInterface
508 * The typed data manager.
510 * @see \Drupal\Core\TypedData\TypedDataManager::create()
512 public static function typedDataManager() {
513 return static::getContainer()->get('typed_data_manager');
517 * Returns the token service.
519 * @return \Drupal\Core\Utility\Token
522 public static function token() {
523 return static::getContainer()->get('token');
527 * Returns the url generator service.
529 * @return \Drupal\Core\Routing\UrlGeneratorInterface
530 * The url generator service.
532 public static function urlGenerator() {
533 return static::getContainer()->get('url_generator');
537 * Generates a URL string for a specific route based on the given parameters.
539 * This method is a convenience wrapper for generating URL strings for URLs
540 * that have Drupal routes (that is, most pages generated by Drupal) using
541 * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
542 * detailed documentation. For non-routed local URIs relative to
543 * the base path (like robots.txt) use Url::fromUri()->toString() with the
546 * @param string $route_name
547 * The name of the route.
548 * @param array $route_parameters
549 * (optional) An associative array of parameter names and values.
550 * @param array $options
551 * (optional) An associative array of additional options.
552 * @param bool $collect_bubbleable_metadata
553 * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
554 * associated bubbleable metadata are returned.
556 * @return string|\Drupal\Core\GeneratedUrl
557 * A string containing a URL to the given path.
558 * When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
559 * returned, containing the generated URL plus bubbleable metadata.
561 * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
562 * @see \Drupal\Core\Url
563 * @see \Drupal\Core\Url::fromRoute()
564 * @see \Drupal\Core\Url::fromUri()
566 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0.
567 * Instead create a \Drupal\Core\Url object directly, for example using
570 public static function url($route_name, $route_parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
571 return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);
575 * Returns the link generator service.
577 * @return \Drupal\Core\Utility\LinkGeneratorInterface
579 public static function linkGenerator() {
580 return static::getContainer()->get('link_generator');
584 * Renders a link with a given link text and Url object.
586 * This method is a convenience wrapper for the link generator service's
589 * @param string $text
590 * The link text for the anchor tag.
591 * @param \Drupal\Core\Url $url
592 * The URL object used for the link.
594 * @return \Drupal\Core\GeneratedLink
595 * A GeneratedLink object containing a link to the given route and
596 * parameters and bubbleable metadata.
598 * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
599 * @see \Drupal\Core\Url
601 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
602 * Use \Drupal\Core\Link instead.
605 * $link = Link::fromTextAndUrl($text, $url);
608 public static function l($text, Url $url) {
609 return static::getContainer()->get('link_generator')->generate($text, $url);
613 * Returns the string translation service.
615 * @return \Drupal\Core\StringTranslation\TranslationManager
616 * The string translation manager.
618 public static function translation() {
619 return static::getContainer()->get('string_translation');
623 * Returns the language manager service.
625 * @return \Drupal\Core\Language\LanguageManagerInterface
626 * The language manager.
628 public static function languageManager() {
629 return static::getContainer()->get('language_manager');
633 * Returns the CSRF token manager service.
635 * The generated token is based on the session ID of the current user. Normally,
636 * anonymous users do not have a session, so the generated token will be
637 * different on every page request. To generate a token for users without a
638 * session, manually start a session prior to calling this function.
640 * @return \Drupal\Core\Access\CsrfTokenGenerator
641 * The CSRF token manager.
643 * @see \Drupal\Core\Session\SessionManager::start()
645 public static function csrfToken() {
646 return static::getContainer()->get('csrf_token');
650 * Returns the transliteration service.
652 * @return \Drupal\Core\Transliteration\PhpTransliteration
653 * The transliteration manager.
655 public static function transliteration() {
656 return static::getContainer()->get('transliteration');
660 * Returns the form builder service.
662 * @return \Drupal\Core\Form\FormBuilderInterface
665 public static function formBuilder() {
666 return static::getContainer()->get('form_builder');
670 * Gets the theme service.
672 * @return \Drupal\Core\Theme\ThemeManagerInterface
674 public static function theme() {
675 return static::getContainer()->get('theme.manager');
679 * Gets the syncing state.
682 * Returns TRUE is syncing flag set.
684 public static function isConfigSyncing() {
685 return static::getContainer()->get('config.installer')->isSyncing();
689 * Returns a channel logger object.
691 * @param string $channel
692 * The name of the channel. Can be any string, but the general practice is
693 * to use the name of the subsystem calling this.
695 * @return \Psr\Log\LoggerInterface
696 * The logger for this channel.
698 public static function logger($channel) {
699 return static::getContainer()->get('logger.factory')->get($channel);
703 * Returns the menu tree.
705 * @return \Drupal\Core\Menu\MenuLinkTreeInterface
708 public static function menuTree() {
709 return static::getContainer()->get('menu.link_tree');
713 * Returns the path validator.
715 * @return \Drupal\Core\Path\PathValidatorInterface
717 public static function pathValidator() {
718 return static::getContainer()->get('path.validator');
722 * Returns the access manager service.
724 * @return \Drupal\Core\Access\AccessManagerInterface
725 * The access manager service.
727 public static function accessManager() {
728 return static::getContainer()->get('access_manager');
732 * Returns the redirect destination helper.
734 * @return \Drupal\Core\Routing\RedirectDestinationInterface
735 * The redirect destination helper.
737 public static function destination() {
738 return static::getContainer()->get('redirect.destination');
742 * Returns the entity definition update manager.
744 * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
745 * The entity definition update manager.
747 public static function entityDefinitionUpdateManager() {
748 return static::getContainer()->get('entity.definition_update_manager');
752 * Returns the time service.
754 * @return \Drupal\Component\Datetime\TimeInterface
757 public static function time() {
758 return static::getContainer()->get('datetime.time');
762 * Returns the messenger.
764 * @return \Drupal\Core\Messenger\MessengerInterface
767 public static function messenger() {
768 // @todo Replace with service once LegacyMessenger is removed in 9.0.0.
769 // @see https://www.drupal.org/node/2928994
770 return new LegacyMessenger();