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.

MINIMUM_SUPPORTED_PHP

Minimum supported version of PHP.

Below this version:

  • New sites cannot be installed, except from within tests.
  • Updates from previous Drupal versions can be run, but users are warned that Drupal no longer supports that PHP version.
  • An error is shown in the status report that the PHP version is too old.

MINIMUM_PHP

Minimum allowed version of PHP for Drupal to be bootstrapped.

Below this version:

  • The installer cannot be run.
  • Updates cannot be run.
  • Modules and themes cannot be enabled.
  • If a site managed to bypass all of the above, then an error is shown in the status report and various fatal errors occur on various pages.

Note: To prevent the installer from having fatal errors on older versions of PHP, the value of this constant is hardcoded twice in core/install.php:

  • Once as a parameter of version_compare()
  • Once in the error message printed to the user immediately after. Remember to update both whenever this constant is updated.

MINIMUM_PHP_MEMORY_LIMIT

Minimum recommended value of PHP memory_limit.

64M was chosen as a minimum requirement in order to allow for additional contributed modules to be installed prior to hitting the limit. However, 40M is the target for the Standard installation profile.

RECOMMENDED_PHP

Minimum recommended version of PHP.

Sites installing Drupal on PHP versions lower than this will see a warning message, but Drupal can still be installed. Used for (e.g.) PHP versions that have reached their EOL or will in the near future.

Properties

static protected ContainerInterface|null $container

The currently active container object, or NULL if not initialized yet.

Methods

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.

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.

static RequestStack
requestStack()

Retrieves the request stack.

routeMatch()

Retrieves the currently active route match object.

currentUser()

Gets the current active user.

entityTypeManager()

Retrieves the entity type manager.

static Connection
database()

Returns the current primary database.

cache(string $bin = 'default')

Returns the requested cache bin.

static ClassResolverInterface|object
classResolver(string $class = NULL)

Retrieves the class resolver.

keyValueExpirable(string $collection)

Returns an expirable key value store collection.

lock()

Returns the locking layer instance.

static ImmutableConfig
config(string $name)

Retrieves a configuration object.

configFactory()

Retrieves the configuration factory.

static QueueInterface
queue(string $name, bool $reliable = FALSE)

Returns a queue for the given queue name.

keyValue(string $collection)

Returns a key/value storage collection.

static StateInterface
state()

Returns the state storage service.

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.

entityQueryAggregate(string $entity_type, string $conjunction = 'AND')

Returns the entity query aggregate object for this entity type.

static FloodInterface
flood()

Returns the flood instance.

moduleHandler()

Returns the module handler.

typedDataManager()

Returns the typed data manager service.

static Token
token()

Returns the token service.

urlGenerator()

Returns the url generator service.

linkGenerator()

Returns the link generator service.

translation()

Returns the string translation service.

languageManager()

Returns the language manager service.

csrfToken()

Returns the CSRF token manager service.

transliteration()

Returns the transliteration service.

formBuilder()

Returns the form builder service.

theme()

Gets the theme service.

static bool
isConfigSyncing()

Gets the syncing state.

static LoggerInterface
logger(string $channel)

Returns a channel logger object.

menuTree()

Returns the menu tree.

pathValidator()

Returns the path validator.

accessManager()

Returns the access manager service.

destination()

Returns the redirect destination helper.

entityDefinitionUpdateManager()

Returns the entity definition update manager.

static TimeInterface
time()

Returns the time service.

messenger()

Returns the messenger.

Details

static setContainer(ContainerInterface $container)

Sets a new global container.

Parameters

ContainerInterface $container

A new container instance to replace the current.

static unsetContainer()

Unsets the global container.

static ContainerInterface getContainer()

Returns the currently active global container.

Return Value

ContainerInterface

Exceptions

ContainerNotInitializedException

static bool hasContainer()

Returns TRUE if the container has been initialized, FALSE otherwise.

Return Value

bool

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.

Parameters

string $id

The ID of the service to retrieve.

Return Value

mixed

The specified service.

static bool hasService(string $id)

Indicates if a service is defined in the container.

Parameters

string $id

The ID of the service to check.

Return Value

bool

TRUE if the specified service exists, FALSE otherwise.

static string root()

Gets the app root.

Return Value

string

static string|null installProfile()

Gets the active install profile.

Return Value

string|null

The name of the active install profile.

static bool hasRequest()

Indicates if there is a currently active request object.

Return Value

bool

TRUE if there is a currently active request object, FALSE otherwise.

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.

Return Value

Request

The currently active request object.

static RequestStack requestStack()

Retrieves the request stack.

Return Value

RequestStack

The request stack

static RouteMatchInterface routeMatch()

Retrieves the currently active route match object.

Return Value

RouteMatchInterface

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:

Return Value

AccountProxyInterface

static EntityTypeManagerInterface entityTypeManager()

Retrieves the entity type manager.

Return Value

EntityTypeManagerInterface

The entity type manager.

static Connection database()

Returns the current primary database.

Return Value

Connection

The current active database's master connection.

static CacheBackendInterface cache(string $bin = 'default')

Returns the requested cache bin.

Parameters

string $bin

(optional) The cache bin for which the cache object should be returned, defaults to 'default'.

Return Value

CacheBackendInterface

The cache object associated with the specified 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.

Parameters

string $class

(optional) A class name to instantiate.

Return Value

ClassResolverInterface|object

The class resolver or if $class is provided, a class instance with a given class definition.

Exceptions

InvalidArgumentException

static KeyValueStoreExpirableInterface keyValueExpirable(string $collection)

Returns an expirable key value store collection.

Parameters

string $collection

The name of the collection holding key and value pairs.

Return Value

KeyValueStoreExpirableInterface

An expirable key value store collection.

static LockBackendInterface lock()

Returns the locking layer instance.

Return Value

LockBackendInterface

static ImmutableConfig config(string $name)

Retrieves a configuration object.

This is the main entry point to the configuration API. Calling

Parameters

string $name

The name of the configuration object to retrieve, which typically corresponds to a configuration file. For @code \Drupal::config('book.admin') @endcode, the configuration object returned will contain the content of the book.admin configuration file.

Return Value

ImmutableConfig

An immutable configuration object.

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.

Return Value

ConfigFactoryInterface

The configuration factory service.

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'.

Parameters

string $name

The name of the queue to work with.

bool $reliable

(optional) TRUE if the ordering of items and guaranteeing every item executes at least once is important, FALSE if scalability is the main concern. Defaults to FALSE.

Return Value

QueueInterface

The queue object for a given name.

static KeyValueStoreInterface keyValue(string $collection)

Returns a key/value storage collection.

Parameters

string $collection

Name of the key/value collection to return.

Return Value

KeyValueStoreInterface

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.

Return Value

StateInterface

static Client httpClient()

Returns the default http client.

Return Value

Client

A guzzle http client instance.

static QueryInterface entityQuery(string $entity_type, string $conjunction = 'AND')

Returns the entity query object for this entity type.

Parameters

string $entity_type

The entity type (for example, node) for which the query object should be returned.

string $conjunction

(optional) Either 'AND' if all conditions in the query need to apply, or 'OR' if any of them is sufficient. Defaults to 'AND'.

Return Value

QueryInterface

The query object that can query the given entity type.

static QueryAggregateInterface entityQueryAggregate(string $entity_type, string $conjunction = 'AND')

Returns the entity query aggregate object for this entity type.

Parameters

string $entity_type

The entity type (for example, node) for which the query object should be returned.

string $conjunction

(optional) Either 'AND' if all conditions in the query need to apply, or 'OR' if any of them is sufficient. Defaults to 'AND'.

Return Value

QueryAggregateInterface

The query object that can query the given entity type.

static FloodInterface flood()

Returns the flood instance.

Return Value

FloodInterface

static ModuleHandlerInterface moduleHandler()

Returns the module handler.

Return Value

ModuleHandlerInterface

static TypedDataManagerInterface typedDataManager()

Returns the typed data manager service.

Use the typed data manager service for creating typed data objects.

Return Value

TypedDataManagerInterface

The typed data manager.

See also

TypedDataManager::create

static Token token()

Returns the token service.

Return Value

Token

The token service.

static UrlGeneratorInterface urlGenerator()

Returns the url generator service.

Return Value

UrlGeneratorInterface

The url generator service.

static LinkGeneratorInterface linkGenerator()

Returns the link generator service.

Return Value

LinkGeneratorInterface

static TranslationManager translation()

Returns the string translation service.

Return Value

TranslationManager

The string translation manager.

static LanguageManagerInterface languageManager()

Returns the language manager service.

Return Value

LanguageManagerInterface

The language manager.

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.

Return Value

CsrfTokenGenerator

The CSRF token manager.

See also

SessionManager::start

static PhpTransliteration transliteration()

Returns the transliteration service.

Return Value

PhpTransliteration

The transliteration manager.

static FormBuilderInterface formBuilder()

Returns the form builder service.

Return Value

FormBuilderInterface

The form builder.

static ThemeManagerInterface theme()

Gets the theme service.

Return Value

ThemeManagerInterface

static bool isConfigSyncing()

Gets the syncing state.

Return Value

bool

Returns TRUE is syncing flag set.

static LoggerInterface logger(string $channel)

Returns a channel logger object.

Parameters

string $channel

The name of the channel. Can be any string, but the general practice is to use the name of the subsystem calling this.

Return Value

LoggerInterface

The logger for this channel.

static MenuLinkTreeInterface menuTree()

Returns the menu tree.

Return Value

MenuLinkTreeInterface

The menu tree.

static PathValidatorInterface pathValidator()

Returns the path validator.

Return Value

PathValidatorInterface

static AccessManagerInterface accessManager()

Returns the access manager service.

Return Value

AccessManagerInterface

The access manager service.

static RedirectDestinationInterface destination()

Returns the redirect destination helper.

Return Value

RedirectDestinationInterface

The redirect destination helper.

static EntityDefinitionUpdateManagerInterface entityDefinitionUpdateManager()

Returns the entity definition update manager.

Return Value

EntityDefinitionUpdateManagerInterface

The entity definition update manager.

static TimeInterface time()

Returns the time service.

Return Value

TimeInterface

The time service.

static MessengerInterface messenger()

Returns the messenger.

Return Value

MessengerInterface

The messenger.