Studying the DrupalKernel Object in Drupal
Request object
DrupalKernel object.
createFromRequest accepts a Request object for use in intializeSettings
Settings object.
Database static method
Kernel handle() does initializeSettings(Request $request) and boot()
DrupalKernel very important service container property, which holds all Drupal services, and notably the http_kernel service, which gives us
Old fashioned ...
GLOBAL $config variable and require statement for settings.php
a $databases array passed to a Database static method.
a $settings array passed to Settings object.
// Initialize databases.
Database::setMultipleConnectionInfo($databases, $class_loader, $app_root);
// Initialize Settings.
new Settings($settings);
In Drupal (and Symfony), these objects and methods form the backbone of the Request/Response lifecycle. They handle everything from the moment a user hits your URL to the moment the database connection is established.
1. The Kernel (The Engine)
The DrupalKernel is the heart of the system. It is responsible for "bootstrapping" Drupal—meaning it sets up the environment, loads the service container, and prepares the site to handle a request.
DrupalKernel(Object): Think of this as the brain of the application. It manages the dependency injection container and coordinates the transition from a raw HTTP request to a Drupal-rendered page.DrupalKernel::createFromRequest: This is a static factory method. It looks at the incoming SymfonyRequestobject to determine where the site is located (the "site path"), which is crucial for multi-site installations where different domains point to different folders.handle(): This is the most important method. It takes aRequestobject, passes it through the middleware stack and the routing system, and returns aResponseobject. It "runs" the application.initializeSettings(): This method locates and loads yoursettings.phpfile. It populates theSettingssingleton with site-specific configuration (like database credentials and hash salts).boot(): This is the physical startup process. It initializes the service container, registers stream wrappers (likepublic://), and ensures the environment is ready for code execution.
2. Infrastructure & Configuration
Settings (The Configuration Store)
The Settings object is a read-only "Singleton" that holds the values from your settings.php file.
Purpose: It’s used for low-level configuration that is needed before the database is even connected (e.g., the
$settings['hash_salt']).Usage:
Settings::get('my_config_key');
Request (The Incoming Data)
This is a Symfony object that represents the HTTP request.
Purpose: It contains everything the user sent: GET/POST parameters, Cookies, Headers, and the URL path.
Usage: In a Controller, you use this to get data:
$request->query->get('page');
3. The Database Layer
Database (The Connection Manager)
The Database class is the entry point for all database interactions. It manages the connections to different targets (like a "default" database and a "replica" or "external" database).
Database::setMultipleConnectionInfo: This is used to register database connection details manually. While Drupal usually does this automatically viasettings.php, this method is used during the installation process or when you need to programmatically connect to an external database on the fly.
How they all work together (The Flow)
index.phpcallsDrupalKernel::createFromRequest.The kernel calls
initializeSettings()to find out where the database is.The kernel calls
boot()to start the services.Databaseuses the info from settings to prepare a connection.The kernel calls
handle($request), which finds your Controller.The Controller returns a Response, and the kernel sends it to the browser.
Next we will see to use the RequestStack service to get the current request inside a custom Service or Form.
In Drupal, you should avoid using the global \Symfony\Component\HttpFoundation\Request object directly. Instead, you use the Request Stack service. This ensures your code is testable and works correctly even during sub-requests (like when one page renders another internal component).
Here is how you use the request_stack service in two common scenarios.
1. Inside a Custom Service (Dependency Injection)
This is the "cleanest" way to access the request. You inject the service via your .services.yml and the constructor.
my_module.services.yml
YAML
services:
my_module.helper:
class: Drupal\my_module\MyHelperService
arguments: ['@request_stack']
src/MyHelperService.php
PHP
namespace Drupal\my_module;
use Symfony\Component\HttpFoundation\RequestStack;
class MyHelperService {
protected $requestStack;
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
public function getClientIp() {
// getCurrentRequest() retrieves the master request currently being handled
$request = $this->requestStack->getCurrentRequest();
return $request ? $request->getClientIp() : NULL;
}
}
2. Inside a Form or Controller
Forms and Controllers in Drupal often have helper methods to access services, but the logic remains the same.
PHP
public function buildForm(array $form, FormStateInterface $form_state) {
// Access the request stack service
$request = \Drupal::service('request_stack')->getCurrentRequest();
// Get a query parameter (?type=special)
$type = $request->query->get('type', 'default');
$form['info'] = [
'#markup' => $this->t('You are viewing the %type version of this form.', ['%type' => $type]),
];
return $form;
}
Why use the Request Stack instead of $_GET?
The Request object provided by the stack is a Symfony object that offers several advantages:
Feature | Using Request Object | Using $_GET or $_POST |
Security | Built-in methods to sanitize and handle input safely. | Manual filtering required (risky). |
Methods |
| Must check |
Parameters |
| Splitting logic between different arrays. |
Testing | Can be mocked in Unit Tests. | Impossible to mock global variables easily. |
Pro-Tip: Accessing the Session
The Request object is also where you access the user's session in a modern, object-oriented way:
PHP
$session = $request->getSession();
$session->set('my_module_variable', 'hello');
$value = $session->get('my_module_variable');
Next we will see how to use the current_route_match service to get the parameters of the URL (like the node ID) without parsing the raw URL string.
While the Request Stack gives you the raw data (the URL string, headers, etc.), the current_route_match service is what translates those raw paths into meaningful Drupal objects.
For example, if you are on the path /node/123, the Request Stack sees the string 123, but the Route Match sees the actual Node entity object.
1. Accessing Route Match in a Service
Just like the Request Stack, you inject the @current_route_match service.
src/MyHelperService.php
PHP
namespace Drupal\my_module;
use Drupal\Core\Routing\RouteMatchInterface;
class MyHelperService {
protected $routeMatch;
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
public function getContextualNodeId() {
// Get the actual parameter from the route.
// If the URL is /node/5, this returns the Node object for ID 5.
$node = $this->routeMatch->getParameter('node');
return ($node instanceof \Drupal\node\NodeInterface) ? $node->id() : NULL;
}
}
2. Common Methods of current_route_match
Method | Description | Example Output |
| The machine name of the route. |
|
| Returns the upcasted object (entity). |
|
| Returns the raw string/ID. |
|
| Returns all parameters. |
|
3. The Difference: Raw vs. Upcasted
Drupal performs "Param Conversion" (upcasting). This is the magic that happens between the Request and the Route Match.
Request Stack: Useful when you need
$_GETvariables like?search=drupalor?page=1.Route Match: Useful when you need to know what Drupal is currently displaying (the Node, the Term, the User).
4. Using it in a Controller
In a Controller, the current route match is often available directly via $this->getRouteMatch().
PHP
public function myAction() {
$route_name = $this->getRouteMatch()->getRouteName();
if ($route_name === 'entity.node.canonical') {
// We are viewing a node page.
}
}
5. Summary of "Current" Services
When building dynamic logic, you will often use these three services together:
@request_stack: For raw HTTP data (Query strings, Cookies).@current_route_match: For Drupal-specific data (Route names, Entities in the URL).@current_user: For the person viewing the page (Roles, UID).
Recent content
-
1 hour 3 minutes ago
-
1 week ago
-
1 week 1 day ago
-
1 week 1 day ago
-
1 week 1 day ago
-
1 week 6 days ago
-
2 weeks ago
-
2 weeks 1 day ago
-
2 weeks 1 day ago
-
2 weeks 2 days ago