Drupal
class Drupal (View source)
Static Service Container wrapper.
Generally, code in Drupal should accept its dependencies via either constructor injection or setter method injection. However, there are cases, particularly in legacy procedural code, where that is infeasible. This class acts as a unified global accessor to arbitrary services within the system in order to ease the transition from procedural code to injected OO code.
The container is built by the kernel and passed in to this class which stores it statically. The container always contains the services from \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other service providers defined in $GLOBALS['conf']['container_service_providers'].
This class exists only to support legacy code that cannot be dependency injected. If your code needs it, consider refactoring it to be object oriented, if possible. When this is not possible, for instance in the case of hook implementations, and your code is more than a few non-reusable lines, it is recommended to instantiate an object implementing the actual logic.
Constants
| VERSION |
The current system version. |
| CORE_COMPATIBILITY |
Core API compatibility. |
| CORE_MINIMUM_SCHEMA_VERSION |
Core minimum schema version. |
Properties
| static protected ContainerInterface|null | $container | The currently active container object, or NULL if not initialized yet. |
Methods
Sets a new global container.
Unsets the global container.
Returns the currently active global container.
Returns TRUE if the container has been initialized, FALSE otherwise.
Retrieves a service from the container.
Indicates if a service is defined in the container.
Gets the app root.
Gets the active install profile.
Indicates if there is a currently active request object.
Retrieves the currently active request object.
Retrieves the request stack.
Retrieves the currently active route match object.
Gets the current active user.
Retrieves the entity type manager.
Returns the current primary database.
Returns the requested cache bin.
Retrieves the class resolver.
Returns an expirable key value store collection.
Returns the locking layer instance.
Retrieves a configuration object.
Retrieves the configuration factory.
Returns a queue for the given queue name.
Returns a key/value storage collection.
Returns the state storage service.
Returns the default http client.
Returns the entity query object for this entity type.
Returns the entity query aggregate object for this entity type.
Returns the flood instance.
Returns the module handler.
Returns the typed data manager service.
Returns the url generator service.
Generates a URL string for a specific route based on the given parameters.
Returns the link generator service.
Renders a link with a given link text and Url object.
Returns the string translation service.
Returns the language manager service.
Returns the CSRF token manager service.
Returns the transliteration service.
Returns the form builder service.
Gets the theme service.
Gets the syncing state.
Returns a channel logger object.
Returns the menu tree.
Returns the path validator.
Returns the access manager service.
Returns the redirect destination helper.
Returns the entity definition update manager.
Returns the time service.
Returns the messenger.
Details
static
setContainer(ContainerInterface $container)
Sets a new global container.
static
unsetContainer()
Unsets the global container.
static ContainerInterface
getContainer()
Returns the currently active global container.
static bool
hasContainer()
Returns TRUE if the container has been initialized, FALSE otherwise.
static mixed
service(string $id)
Retrieves a service from the container.
Use this method if the desired service is not one of those with a dedicated accessor method below. If it is listed below, those methods are preferred as they can return useful type hints.
static bool
hasService(string $id)
Indicates if a service is defined in the container.
static string
root()
Gets the app root.
static string|null
installProfile()
Gets the active install profile.
static bool
hasRequest()
Indicates if there is a currently active request object.
static Request
request()
Retrieves the currently active request object.
Note: The use of this wrapper in particular is especially discouraged. Most code should not need to access the request directly. Doing so means it will only function when handling an HTTP request, and will require special modification or wrapping when run from a command line tool, from certain queue processors, or from automated tests.
If code must access the request, it is considerably better to register an object with the Service Container and give it a setRequest() method that is configured to run when the service is created. That way, the correct request object can always be provided by the container and the service can still be unit tested.
If this method must be used, never save the request object that is returned. Doing so may lead to inconsistencies as the request object is volatile and may change at various times, such as during a subrequest.
static RequestStack
requestStack()
Retrieves the request stack.
static RouteMatchInterface
routeMatch()
Retrieves the currently active route match object.
static AccountProxyInterface
currentUser()
Gets the current active user.
This method will return the \Drupal\Core\Session\AccountProxy object of the current user. You can use the \Drupal\user\Entity\User::load() method to load the full user entity object. For example:
static EntityManagerInterface
entityManager()
deprecated
deprecated
Retrieves the entity manager service.
static EntityTypeManagerInterface
entityTypeManager()
Retrieves the entity type manager.
static Connection
database()
Returns the current primary database.
static CacheBackendInterface
cache(string $bin = 'default')
Returns the requested cache bin.
static ClassResolverInterface|object
classResolver(string $class = NULL)
Retrieves the class resolver.
This is to be used in procedural code such as module files to instantiate an object of a class that implements \Drupal\Core\DependencyInjection\ContainerInjectionInterface.
One common usecase is to provide a class which contains the actual code of a hook implementation, without having to create a service.
static KeyValueStoreExpirableInterface
keyValueExpirable(string $collection)
Returns an expirable key value store collection.
static LockBackendInterface
lock()
Returns the locking layer instance.
static ImmutableConfig
config(string $name)
Retrieves a configuration object.
This is the main entry point to the configuration API. Calling
static ConfigFactoryInterface
configFactory()
Retrieves the configuration factory.
This is mostly used to change the override settings on the configuration factory. For example, changing the language, or turning all overrides on or off.
static QueueInterface
queue(string $name, bool $reliable = FALSE)
Returns a queue for the given queue name.
The following values can be set in your settings.php file's $settings array to define which services are used for queues:
- queue_reliableservice$name: The container service to use for the reliable queue $name.
- queueservice$name: The container service to use for the queue $name.
- queue_default: The container service to use by default for queues without overrides. This defaults to 'queue.database'.
static KeyValueStoreInterface
keyValue(string $collection)
Returns a key/value storage collection.
static StateInterface
state()
Returns the state storage service.
Use this to store machine-generated data, local to a specific environment that does not need deploying and does not need human editing; for example, the last time cron was run. Data which needs to be edited by humans and needs to be the same across development, production, etc. environments (for example, the system maintenance message) should use \Drupal::config() instead.
static Client
httpClient()
Returns the default http client.
static QueryInterface
entityQuery(string $entity_type, string $conjunction = 'AND')
Returns the entity query object for this entity type.
static QueryAggregateInterface
entityQueryAggregate(string $entity_type, string $conjunction = 'AND')
Returns the entity query aggregate object for this entity type.
static FloodInterface
flood()
Returns the flood instance.
static ModuleHandlerInterface
moduleHandler()
Returns the module handler.
static TypedDataManagerInterface
typedDataManager()
Returns the typed data manager service.
Use the typed data manager service for creating typed data objects.
static Token
token()
Returns the token service.
static UrlGeneratorInterface
urlGenerator()
Returns the url generator service.
static string|GeneratedUrl
url(string $route_name, array $route_parameters = [], array $options = [], bool $collect_bubbleable_metadata = FALSE)
deprecated
deprecated
Generates a URL string for a specific route based on the given parameters.
This method is a convenience wrapper for generating URL strings for URLs that have Drupal routes (that is, most pages generated by Drupal) using the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for detailed documentation. For non-routed local URIs relative to the base path (like robots.txt) use Url::fromUri()->toString() with the base: scheme.
static LinkGeneratorInterface
linkGenerator()
Returns the link generator service.
static GeneratedLink
l(string|array|MarkupInterface $text, Url $url)
deprecated
deprecated
Renders a link with a given link text and Url object.
This method is a convenience wrapper for the link generator service's generate() method.
static TranslationManager
translation()
Returns the string translation service.
static LanguageManagerInterface
languageManager()
Returns the language manager service.
static CsrfTokenGenerator
csrfToken()
Returns the CSRF token manager service.
The generated token is based on the session ID of the current user. Normally, anonymous users do not have a session, so the generated token will be different on every page request. To generate a token for users without a session, manually start a session prior to calling this function.
static PhpTransliteration
transliteration()
Returns the transliteration service.
static FormBuilderInterface
formBuilder()
Returns the form builder service.
static ThemeManagerInterface
theme()
Gets the theme service.
static bool
isConfigSyncing()
Gets the syncing state.
static LoggerInterface
logger(string $channel)
Returns a channel logger object.
static MenuLinkTreeInterface
menuTree()
Returns the menu tree.
static PathValidatorInterface
pathValidator()
Returns the path validator.
static AccessManagerInterface
accessManager()
Returns the access manager service.
static RedirectDestinationInterface
destination()
Returns the redirect destination helper.
static EntityDefinitionUpdateManagerInterface
entityDefinitionUpdateManager()
Returns the entity definition update manager.
static TimeInterface
time()
Returns the time service.
static MessengerInterface
messenger()
Returns the messenger.