8 use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
13 * Static Service Container wrapper.
15 * Generally, code in Drupal should accept its dependencies via either
16 * constructor injection or setter method injection. However, there are cases,
17 * particularly in legacy procedural code, where that is infeasible. This
18 * class acts as a unified global accessor to arbitrary services within the
19 * system in order to ease the transition from procedural code to injected OO
22 * The container is built by the kernel and passed in to this class which stores
23 * it statically. The container always contains the services from
24 * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
25 * service providers defined in $GLOBALS['conf']['container_service_providers'].
27 * This class exists only to support legacy code that cannot be dependency
28 * injected. If your code needs it, consider refactoring it to be object
29 * oriented, if possible. When this is not possible, for instance in the case of
30 * hook implementations, and your code is more than a few non-reusable lines, it
31 * is recommended to instantiate an object implementing the actual logic.
34 * // Legacy procedural code.
35 * function hook_do_stuff() {
36 * $lock = lock()->acquire('stuff_lock');
40 * // Correct procedural code.
41 * function hook_do_stuff() {
42 * $lock = \Drupal::lock()->acquire('stuff_lock');
46 * // The preferred way: dependency injected code.
47 * function hook_do_stuff() {
48 * // Move the actual implementation to a class and instantiate it.
49 * $instance = new StuffDoingClass(\Drupal::lock());
50 * $instance->doStuff();
52 * // Or, even better, rely on the service container to avoid hard coding a
53 * // specific interface implementation, so that the actual logic can be
54 * // swapped. This might not always make sense, but in general it is a good
56 * \Drupal::service('stuff.doing')->doStuff();
59 * interface StuffDoingInterface {
60 * public function doStuff();
63 * class StuffDoingClass implements StuffDoingInterface {
64 * protected $lockBackend;
66 * public function __construct(LockBackendInterface $lock_backend) {
67 * $this->lockBackend = $lock_backend;
70 * public function doStuff() {
71 * $lock = $this->lockBackend->acquire('stuff_lock');
77 * @see \Drupal\Core\DrupalKernel
82 * The current system version.
84 const VERSION = '8.3.7';
87 * Core API compatibility.
89 const CORE_COMPATIBILITY = '8.x';
92 * Core minimum schema version.
94 const CORE_MINIMUM_SCHEMA_VERSION = 8000;
97 * The currently active container object, or NULL if not initialized yet.
99 * @var \Symfony\Component\DependencyInjection\ContainerInterface|null
101 protected static $container;
104 * Sets a new global container.
106 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
107 * A new container instance to replace the current.
109 public static function setContainer(ContainerInterface $container) {
110 static::$container = $container;
114 * Unsets the global container.
116 public static function unsetContainer() {
117 static::$container = NULL;
121 * Returns the currently active global container.
123 * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
125 * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
127 public static function getContainer() {
128 if (static::$container === NULL) {
129 throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.');
131 return static::$container;
135 * Returns TRUE if the container has been initialized, FALSE otherwise.
139 public static function hasContainer() {
140 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 * Retrives 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 * @return \Drupal\Core\DependencyInjection\ClassResolverInterface
323 * The class resolver.
325 public static function classResolver() {
326 return static::getContainer()->get('class_resolver');
330 * Returns an expirable key value store collection.
332 * @param string $collection
333 * The name of the collection holding key and value pairs.
335 * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
336 * An expirable key value store collection.
338 public static function keyValueExpirable($collection) {
339 return static::getContainer()->get('keyvalue.expirable')->get($collection);
343 * Returns the locking layer instance.
345 * @return \Drupal\Core\Lock\LockBackendInterface
349 public static function lock() {
350 return static::getContainer()->get('lock');
354 * Retrieves a configuration object.
356 * This is the main entry point to the configuration API. Calling
357 * @code \Drupal::config('book.admin') @endcode will return a configuration
358 * object in which the book module can store its administrative settings.
360 * @param string $name
361 * The name of the configuration object to retrieve. The name corresponds to
362 * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
363 * object returned will contain the contents of book.admin configuration file.
365 * @return \Drupal\Core\Config\ImmutableConfig
366 * An immutable configuration object.
368 public static function config($name) {
369 return static::getContainer()->get('config.factory')->get($name);
373 * Retrieves the configuration factory.
375 * This is mostly used to change the override settings on the configuration
376 * factory. For example, changing the language, or turning all overrides on
379 * @return \Drupal\Core\Config\ConfigFactoryInterface
380 * The configuration factory service.
382 public static function configFactory() {
383 return static::getContainer()->get('config.factory');
387 * Returns a queue for the given queue name.
389 * The following values can be set in your settings.php file's $settings
390 * array to define which services are used for queues:
391 * - queue_reliable_service_$name: The container service to use for the
392 * reliable queue $name.
393 * - queue_service_$name: The container service to use for the
395 * - queue_default: The container service to use by default for queues
396 * without overrides. This defaults to 'queue.database'.
398 * @param string $name
399 * The name of the queue to work with.
400 * @param bool $reliable
401 * (optional) TRUE if the ordering of items and guaranteeing every item
402 * executes at least once is important, FALSE if scalability is the main
403 * concern. Defaults to FALSE.
405 * @return \Drupal\Core\Queue\QueueInterface
406 * The queue object for a given name.
408 public static function queue($name, $reliable = FALSE) {
409 return static::getContainer()->get('queue')->get($name, $reliable);
413 * Returns a key/value storage collection.
415 * @param string $collection
416 * Name of the key/value collection to return.
418 * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
420 public static function keyValue($collection) {
421 return static::getContainer()->get('keyvalue')->get($collection);
425 * Returns the state storage service.
427 * Use this to store machine-generated data, local to a specific environment
428 * that does not need deploying and does not need human editing; for example,
429 * the last time cron was run. Data which needs to be edited by humans and
430 * needs to be the same across development, production, etc. environments
431 * (for example, the system maintenance message) should use \Drupal::config() instead.
433 * @return \Drupal\Core\State\StateInterface
435 public static function state() {
436 return static::getContainer()->get('state');
440 * Returns the default http client.
442 * @return \GuzzleHttp\Client
443 * A guzzle http client instance.
445 public static function httpClient() {
446 return static::getContainer()->get('http_client');
450 * Returns the entity query object for this entity type.
452 * @param string $entity_type
453 * The entity type (for example, node) for which the query object should be
455 * @param string $conjunction
456 * (optional) Either 'AND' if all conditions in the query need to apply, or
457 * 'OR' if any of them is sufficient. Defaults to 'AND'.
459 * @return \Drupal\Core\Entity\Query\QueryInterface
460 * The query object that can query the given entity type.
462 public static function entityQuery($entity_type, $conjunction = 'AND') {
463 return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction);
467 * Returns the entity query aggregate object for this entity type.
469 * @param string $entity_type
470 * The entity type (for example, node) for which the query object should be
472 * @param string $conjunction
473 * (optional) Either 'AND' if all conditions in the query need to apply, or
474 * 'OR' if any of them is sufficient. Defaults to 'AND'.
476 * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
477 * The query object that can query the given entity type.
479 public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
480 return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction);
484 * Returns the flood instance.
486 * @return \Drupal\Core\Flood\FloodInterface
488 public static function flood() {
489 return static::getContainer()->get('flood');
493 * Returns the module handler.
495 * @return \Drupal\Core\Extension\ModuleHandlerInterface
497 public static function moduleHandler() {
498 return static::getContainer()->get('module_handler');
502 * Returns the typed data manager service.
504 * Use the typed data manager service for creating typed data objects.
506 * @return \Drupal\Core\TypedData\TypedDataManagerInterface
507 * The typed data manager.
509 * @see \Drupal\Core\TypedData\TypedDataManager::create()
511 public static function typedDataManager() {
512 return static::getContainer()->get('typed_data_manager');
516 * Returns the token service.
518 * @return \Drupal\Core\Utility\Token
521 public static function token() {
522 return static::getContainer()->get('token');
526 * Returns the url generator service.
528 * @return \Drupal\Core\Routing\UrlGeneratorInterface
529 * The url generator service.
531 public static function urlGenerator() {
532 return static::getContainer()->get('url_generator');
536 * Generates a URL string for a specific route based on the given parameters.
538 * This method is a convenience wrapper for generating URL strings for URLs
539 * that have Drupal routes (that is, most pages generated by Drupal) using
540 * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
541 * detailed documentation. For non-routed local URIs relative to
542 * the base path (like robots.txt) use Url::fromUri()->toString() with the
545 * @param string $route_name
546 * The name of the route.
547 * @param array $route_parameters
548 * (optional) An associative array of parameter names and values.
549 * @param array $options
550 * (optional) An associative array of additional options.
551 * @param bool $collect_bubbleable_metadata
552 * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
553 * associated bubbleable metadata are returned.
555 * @return string|\Drupal\Core\GeneratedUrl
556 * A string containing a URL to the given path.
557 * When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
558 * returned, containing the generated URL plus bubbleable metadata.
560 * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
561 * @see \Drupal\Core\Url
562 * @see \Drupal\Core\Url::fromRoute()
563 * @see \Drupal\Core\Url::fromUri()
565 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0.
566 * Instead create a \Drupal\Core\Url object directly, for example using
569 public static function url($route_name, $route_parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
570 return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);
574 * Returns the link generator service.
576 * @return \Drupal\Core\Utility\LinkGeneratorInterface
578 public static function linkGenerator() {
579 return static::getContainer()->get('link_generator');
583 * Renders a link with a given link text and Url object.
585 * This method is a convenience wrapper for the link generator service's
588 * @param string $text
589 * The link text for the anchor tag.
590 * @param \Drupal\Core\Url $url
591 * The URL object used for the link.
593 * @return \Drupal\Core\GeneratedLink
594 * A GeneratedLink object containing a link to the given route and
595 * parameters and bubbleable metadata.
597 * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
598 * @see \Drupal\Core\Url
600 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
601 * Use \Drupal\Core\Link instead.
604 * $link = Link::fromTextAndUrl($text, $url);
607 public static function l($text, Url $url) {
608 return static::getContainer()->get('link_generator')->generate($text, $url);
612 * Returns the string translation service.
614 * @return \Drupal\Core\StringTranslation\TranslationManager
615 * The string translation manager.
617 public static function translation() {
618 return static::getContainer()->get('string_translation');
622 * Returns the language manager service.
624 * @return \Drupal\Core\Language\LanguageManagerInterface
625 * The language manager.
627 public static function languageManager() {
628 return static::getContainer()->get('language_manager');
632 * Returns the CSRF token manager service.
634 * The generated token is based on the session ID of the current user. Normally,
635 * anonymous users do not have a session, so the generated token will be
636 * different on every page request. To generate a token for users without a
637 * session, manually start a session prior to calling this function.
639 * @return \Drupal\Core\Access\CsrfTokenGenerator
640 * The CSRF token manager.
642 * @see \Drupal\Core\Session\SessionManager::start()
644 public static function csrfToken() {
645 return static::getContainer()->get('csrf_token');
649 * Returns the transliteration service.
651 * @return \Drupal\Core\Transliteration\PhpTransliteration
652 * The transliteration manager.
654 public static function transliteration() {
655 return static::getContainer()->get('transliteration');
659 * Returns the form builder service.
661 * @return \Drupal\Core\Form\FormBuilderInterface
664 public static function formBuilder() {
665 return static::getContainer()->get('form_builder');
669 * Gets the theme service.
671 * @return \Drupal\Core\Theme\ThemeManagerInterface
673 public static function theme() {
674 return static::getContainer()->get('theme.manager');
678 * Gets the syncing state.
681 * Returns TRUE is syncing flag set.
683 public static function isConfigSyncing() {
684 return static::getContainer()->get('config.installer')->isSyncing();
688 * Returns a channel logger object.
690 * @param string $channel
691 * The name of the channel. Can be any string, but the general practice is
692 * to use the name of the subsystem calling this.
694 * @return \Psr\Log\LoggerInterface
695 * The logger for this channel.
697 public static function logger($channel) {
698 return static::getContainer()->get('logger.factory')->get($channel);
702 * Returns the menu tree.
704 * @return \Drupal\Core\Menu\MenuLinkTreeInterface
707 public static function menuTree() {
708 return static::getContainer()->get('menu.link_tree');
712 * Returns the path validator.
714 * @return \Drupal\Core\Path\PathValidatorInterface
716 public static function pathValidator() {
717 return static::getContainer()->get('path.validator');
721 * Returns the access manager service.
723 * @return \Drupal\Core\Access\AccessManagerInterface
724 * The access manager service.
726 public static function accessManager() {
727 return static::getContainer()->get('access_manager');
731 * Returns the redirect destination helper.
733 * @return \Drupal\Core\Routing\RedirectDestinationInterface
734 * The redirect destination helper.
736 public static function destination() {
737 return static::getContainer()->get('redirect.destination');
741 * Returns the entity definition update manager.
743 * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
744 * The entity definition update manager.
746 public static function entityDefinitionUpdateManager() {
747 return static::getContainer()->get('entity.definition_update_manager');
751 * Returns the time service.
753 * @return \Drupal\Component\Datetime\TimeInterface
756 public static function time() {
757 return static::getContainer()->get('datetime.time');