class DrupalKernel implements DrupalKernelInterface, TerminableInterface (View source)

The DrupalKernel class is the core of Drupal itself.

This class is responsible for building the Dependency Injection Container and also deals with the registration of service providers. It allows registered service providers to add their services to the container. Core provides the CoreServiceProvider, which, in addition to registering any core services that cannot be registered in the core.services.yaml file, adds any compiler passes needed by core, e.g. for processing tagged services. Each module can add its own service provider, i.e. a class implementing Drupal\Core\DependencyInjection\ServiceProvider, to register services to the container, or modify existing services.

Traits

Provides methods for checking if Drupal is already installed.

Properties

protected string $phpArrayDumperClass

Holds the class used for dumping the container to a PHP array.

protected array $defaultBootstrapContainerDefinition

Holds the default bootstrap container definition.

protected string $bootstrapContainerClass

Holds the class used for instantiating the bootstrap container.

protected ContainerInterface $bootstrapContainer

Holds the bootstrap container.

protected ContainerInterface $container

Holds the container instance.

protected string $environment

The environment, e.g. 'testing', 'install'.

protected bool $booted

Whether the kernel has been booted.

protected bool $prepared

Whether essential services have been set up properly by preHandle().

protected array $moduleList

Holds the list of enabled modules.

protected Extension[] $moduleData

List of available modules and installation profiles.

protected ClassLoader $classLoader

The class loader object.

protected StorageInterface $configStorage

Config storage object used for reading enabled modules configuration.

protected bool $allowDumping

Whether the container can be dumped.

protected bool $containerNeedsRebuild

Whether the container needs to be rebuilt the next time it is initialized.

protected bool $containerNeedsDumping

Whether the container needs to be dumped once booting is complete.

protected array $serviceYamls

List of discovered services.yml pathnames.

protected array $serviceProviderClasses

List of discovered service provider class names or objects.

protected array $serviceProviders

List of instantiated service provider classes.

static protected bool $isEnvironmentInitialized

Whether the PHP environment has been initialized.

protected string $sitePath

The site directory.

protected string $root

The app root.

Methods

bool
isCli()

Returns whether the current PHP process runs on CLI.

bool
shouldRedirectToInstaller(Exception $exception, Connection $connection = NULL)

Determines if an exception handler should redirect to the installer.

static DrupalKernel
createFromRequest(Request $request, $class_loader, string $environment, bool $allow_dumping = TRUE, string $app_root = NULL)

Create a DrupalKernel object from a request.

__construct(string $environment, $class_loader, bool $allow_dumping = TRUE, string $app_root = NULL)

Constructs a DrupalKernel object.

static string
guessApplicationRoot()

Determine the application root directory based on this file's location.

static string
findSitePath(Request $request, bool $require_settings = TRUE, string $app_root = NULL)

Returns the appropriate site directory for a request.

setSitePath(string $path)

Set the current site path.

string
getSitePath()

Get the site path.

string
getAppRoot()

Gets the app root.

$this
boot()

Boots the current kernel.

shutdown()

Shuts down the kernel.

ContainerInterface
getContainer()

Gets the current container.

setContainer(ContainerInterface $container = NULL)

{@inheritdoc}

array|null
getCachedContainerDefinition()

Returns the cached container definition - if any.

loadLegacyIncludes()

Helper method that loads legacy Drupal include files.

preHandle(Request $request)

Helper method that does request related initialization.

array
discoverServiceProviders()

Discovers available serviceProviders.

array
getServiceProviders(string $origin)

Returns all registered service providers.

terminate(Request $request, Response $response)

{@inheritdoc}

handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)

{@inheritdoc}

Response
handleException(Exception $e, Request $request, int $type)

Converts an exception into a response.

Extension|bool
moduleData($module)

Returns module data on the filesystem.

updateModules(array $module_list, array $module_filenames = [])

Implements Drupal\Core\DrupalKernelInterface::updateModules().

string
getContainerCacheKey()

Returns the container cache key based on the environment.

array
getKernelParameters()

Returns the kernel parameters.

ContainerInterface
initializeContainer()

Initializes the service container.

static 
bootEnvironment(string $app_root = NULL)

Setup a consistent PHP environment.

initializeSettings(Request $request)

Locate site path and initialize settings singleton.

initializeRequestGlobals(Request $request)

Bootstraps the legacy global request variables.

getServicesToPersist(ContainerInterface $container)

Returns service instances to persist from an old container to a new one.

persistServices(ContainerInterface $container, array $persist)

Moves persistent service instances into a new container.

ContainerInterface
rebuildContainer()

Force a container rebuild.

invalidateContainer()

Invalidate the service container for the next request.

ContainerInterface
attachSynthetic(ContainerInterface $container)

Attach synthetic values on to kernel.

compileContainer()

Compiles a new service container.

initializeServiceProviders()

Registers all service providers to the kernel.

getContainerBuilder()

Gets a new ContainerBuilder instance used to build the service container.

bool
cacheDrupalContainer(array $container_definition)

Stores the container definition in a cache.

HttpKernelInterface
getHttpKernel()

Gets a http kernel from the container.

getConfigStorage()

Returns the active configuration storage to use during building the container.

array
getModulesParameter()

Returns an array of Extension class parameters for all enabled modules.

array
getModuleFileNames()

Gets the file name for each enabled module.

string[]
getModuleNamespacesPsr4(string[] $module_file_names)

Gets the PSR-4 base directories for module namespaces.

classLoaderAddMultiplePsr4(array $namespaces = [], object $class_loader = NULL)

Registers a list of namespaces with PSR-4 directories for class loading.

static bool
validateHostnameLength(string $host)

Validates a hostname length.

static bool
validateHostname(Request $request)

Validates the hostname supplied from the HTTP request.

static bool
setupTrustedHosts(Request $request, array $host_patterns)

Sets up the lists of trusted HTTP Host headers.

addServiceFiles(array $service_yamls)

Add service files.

string|null
getInstallProfile()

Gets the active install profile.

Details

protected bool isCli()

Returns whether the current PHP process runs on CLI.

Return Value

bool

protected bool shouldRedirectToInstaller(Exception $exception, Connection $connection = NULL)

Determines if an exception handler should redirect to the installer.

Parameters

Exception $exception

The exception to check.

Connection $connection

(optional) The default database connection. If not provided, a less comprehensive check will be performed. This can be the case if the exception occurs early enough that a database connection object isn't available from the container yet.

Return Value

bool

TRUE if the exception handler should redirect to the installer because Drupal is not installed yet, or FALSE otherwise.

static DrupalKernel createFromRequest(Request $request, $class_loader, string $environment, bool $allow_dumping = TRUE, string $app_root = NULL)

Create a DrupalKernel object from a request.

Parameters

Request $request

The request.

$class_loader

The class loader. Normally Composer's ClassLoader, as included by the front controller, but may also be decorated.

string $environment

String indicating the environment, e.g. 'prod' or 'dev'.

bool $allow_dumping

(optional) FALSE to stop the container from being written to or read from disk. Defaults to TRUE.

string $app_root

(optional) The path to the application root as a string. If not supplied, the application root will be computed.

Return Value

DrupalKernel

Exceptions

BadRequestHttpException

__construct(string $environment, $class_loader, bool $allow_dumping = TRUE, string $app_root = NULL)

Constructs a DrupalKernel object.

Parameters

string $environment

String indicating the environment, e.g. 'prod' or 'dev'.

$class_loader

The class loader. Normally \Composer\Autoload\ClassLoader, as included by the front controller, but may also be decorated.

bool $allow_dumping

(optional) FALSE to stop the container from being written to or read from disk. Defaults to TRUE.

string $app_root

(optional) The path to the application root as a string. If not supplied, the application root will be computed.

static protected string guessApplicationRoot()

Determine the application root directory based on this file's location.

Return Value

string

The application root.

static string findSitePath(Request $request, bool $require_settings = TRUE, string $app_root = NULL)

Returns the appropriate site directory for a request.

Once the kernel has been created DrupalKernelInterface::getSitePath() is preferred since it gets the statically cached result of this method.

Site directories contain all site specific code. This includes settings.php for bootstrap level configuration, file configuration stores, public file storage and site specific modules and themes.

A file named sites.php must be present in the sites directory for multisite. If it doesn't exist, then 'sites/default' will be used.

Finds a matching site directory file by stripping the website's hostname from left to right and pathname from right to left. By default, the directory must contain a 'settings.php' file for it to match. If the parameter $require_settings is set to FALSE, then a directory without a 'settings.php' file will match as well. The first configuration file found will be used and the remaining ones will be ignored. If no configuration file is found, returns a default value 'sites/default'. See default.settings.php for examples on how the URL is converted to a directory.

The sites.php file in the sites directory can define aliases in an associative array named $sites. The array is written in the format '..' => 'directory'. As an example, to create a directory alias for https://www.drupal.org:8080/mysite/test whose configuration file is in sites/example.com, the array should be defined as:

Parameters

Request $request

The current request.

bool $require_settings

Only directories with an existing settings.php file will be recognized. Defaults to TRUE. During initial installation, this is set to FALSE so that Drupal can detect a matching directory, then create a new settings.php file in it.

string $app_root

(optional) The path to the application root as a string. If not supplied, the application root will be computed.

Return Value

string

The path of the matching directory.

Exceptions

BadRequestHttpException

See also

DrupalKernelInterface::getSitePath
DrupalKernelInterface::setSitePath
default.settings.php
example.sites.php

setSitePath(string $path)

Set the current site path.

Parameters

string $path

The current site path.

Exceptions

LogicException

string getSitePath()

Get the site path.

Return Value

string

The current site path.

string getAppRoot()

Gets the app root.

Return Value

string

$this boot()

Boots the current kernel.

Return Value

$this

shutdown()

Shuts down the kernel.

ContainerInterface getContainer()

Gets the current container.

Return Value

ContainerInterface

A ContainerInterface instance.

setContainer(ContainerInterface $container = NULL)

{@inheritdoc}

Parameters

ContainerInterface $container

array|null getCachedContainerDefinition()

Returns the cached container definition - if any.

This also allows inspecting a built container for debugging purposes.

Return Value

array|null

The cached container definition or NULL if not found in cache.

loadLegacyIncludes()

Helper method that loads legacy Drupal include files.

preHandle(Request $request)

Helper method that does request related initialization.

Parameters

Request $request

The current request.

array discoverServiceProviders()

Discovers available serviceProviders.

Return Value

array

The available serviceProviders.

array getServiceProviders(string $origin)

Returns all registered service providers.

Parameters

string $origin

The origin for which to return service providers; one of 'app' or 'site'.

Return Value

array

An associative array of ServiceProvider objects, keyed by name.

terminate(Request $request, Response $response)

{@inheritdoc}

Parameters

Request $request
Response $response

handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)

{@inheritdoc}

Parameters

Request $request
$type
$catch

protected Response handleException(Exception $e, Request $request, int $type)

Converts an exception into a response.

Parameters

Exception $e

An exception

Request $request

A Request instance

int $type

The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)

Return Value

Response

A Response instance

Exceptions

Exception

protected Extension|bool moduleData($module)

Returns module data on the filesystem.

Parameters

$module

The name of the module.

Return Value

Extension|bool

Returns an Extension object if the module is found, FALSE otherwise.

updateModules(array $module_list, array $module_filenames = [])

Implements Drupal\Core\DrupalKernelInterface::updateModules().

Remove obsolete $module_list parameter. Only $module_filenames is needed.

Parameters

array $module_list

The new list of modules.

array $module_filenames

List of module filenames, keyed by module name.

protected string getContainerCacheKey()

Returns the container cache key based on the environment.

The 'environment' consists of:

  • The kernel environment string.
  • The Drupal version constant.
  • The deployment identifier from settings.php. This allows custom deployments to force a container rebuild.
  • The operating system running PHP. This allows compiler passes to optimize services for different operating systems.
  • The paths to any additional container YAMLs from settings.php.

Return Value

string

The cache key used for the service container.

protected array getKernelParameters()

Returns the kernel parameters.

Return Value

array

An array of kernel parameters

protected ContainerInterface initializeContainer()

Initializes the service container.

Return Value

ContainerInterface

static bootEnvironment(string $app_root = NULL)

Setup a consistent PHP environment.

This method sets PHP environment options we want to be sure are set correctly for security or just saneness.

Parameters

string $app_root

(optional) The path to the application root as a string. If not supplied, the application root will be computed.

protected initializeSettings(Request $request)

Locate site path and initialize settings singleton.

Parameters

Request $request

The current request.

Exceptions

BadRequestHttpException

protected initializeRequestGlobals(Request $request)

Bootstraps the legacy global request variables.

D8: Eliminate this entirely in favor of Request object.

Parameters

Request $request

The current request.

protected getServicesToPersist(ContainerInterface $container)

Returns service instances to persist from an old container to a new one.

Parameters

ContainerInterface $container

protected persistServices(ContainerInterface $container, array $persist)

Moves persistent service instances into a new container.

Parameters

ContainerInterface $container
array $persist

ContainerInterface rebuildContainer()

Force a container rebuild.

Return Value

ContainerInterface

invalidateContainer()

Invalidate the service container for the next request.

protected ContainerInterface attachSynthetic(ContainerInterface $container)

Attach synthetic values on to kernel.

Parameters

ContainerInterface $container

Container object

Return Value

ContainerInterface

protected ContainerBuilder compileContainer()

Compiles a new service container.

Return Value

ContainerBuilder

The compiled service container

protected initializeServiceProviders()

Registers all service providers to the kernel.

Exceptions

LogicException

protected ContainerBuilder getContainerBuilder()

Gets a new ContainerBuilder instance used to build the service container.

Return Value

ContainerBuilder

protected bool cacheDrupalContainer(array $container_definition)

Stores the container definition in a cache.

Parameters

array $container_definition

The container definition to cache.

Return Value

bool

TRUE if the container was successfully cached.

protected HttpKernelInterface getHttpKernel()

Gets a http kernel from the container.

Return Value

HttpKernelInterface

protected StorageInterface getConfigStorage()

Returns the active configuration storage to use during building the container.

Return Value

StorageInterface

protected array getModulesParameter()

Returns an array of Extension class parameters for all enabled modules.

Return Value

array

protected array getModuleFileNames()

Gets the file name for each enabled module.

Return Value

array

Array where each key is a module name, and each value is a path to the respective *.info.yml file.

protected string[] getModuleNamespacesPsr4(string[] $module_file_names)

Gets the PSR-4 base directories for module namespaces.

Parameters

string[] $module_file_names

Array where each key is a module name, and each value is a path to the respective *.info.yml file.

Return Value

string[]

Array where each key is a module namespace like 'Drupal\system', and each value is the PSR-4 base directory associated with the module namespace.

protected classLoaderAddMultiplePsr4(array $namespaces = [], object $class_loader = NULL)

Registers a list of namespaces with PSR-4 directories for class loading.

Parameters

array $namespaces

Array where each key is a namespace like 'Drupal\system', and each value is either a PSR-4 base directory, or an array of PSR-4 base directories associated with this namespace.

object $class_loader

The class loader. Normally \Composer\Autoload\ClassLoader, as included by the front controller, but may also be decorated; e.g., \Symfony\Component\ClassLoader\ApcClassLoader.

static protected bool validateHostnameLength(string $host)

Validates a hostname length.

Parameters

string $host

A hostname.

Return Value

bool

TRUE if the length is appropriate, or FALSE otherwise.

static bool validateHostname(Request $request)

Validates the hostname supplied from the HTTP request.

Parameters

Request $request

The request object

Return Value

bool

TRUE if the hostname is valid, or FALSE otherwise.

static protected bool setupTrustedHosts(Request $request, array $host_patterns)

Sets up the lists of trusted HTTP Host headers.

Since the HTTP Host header can be set by the user making the request, it is possible to create an attack vectors against a site by overriding this. Symfony provides a mechanism for creating a list of trusted Host values.

Host patterns (as regular expressions) can be configured through settings.php for multisite installations, sites using ServerAlias without canonical redirection, or configurations where the site responds to default requests. For example,

Parameters

Request $request

The request object.

array $host_patterns

The array of trusted host patterns.

Return Value

bool

TRUE if the Host header is trusted, FALSE otherwise.

See also

https://www.drupal.org/docs/8/install/trusted-host-settings
TrustedHostsRequestFactory

protected addServiceFiles(array $service_yamls)

Add service files.

Parameters

array $service_yamls

A list of service files.

protected string|null getInstallProfile()

Gets the active install profile.

Return Value

string|null

The name of the any active install profile or distribution.