Drupal 10: Accessing Settings From The Site settings.php File

Drupal's settings.php file allows you to add arbitrary settings for various purposes.

In your settings file you might have some random setting like this:

$settings['my_custom_settings']['value'] = 'setting';

You would access this in your code using the Settings service:

use Drupal\Core\Site\Settings;
$mysettings = Settings::get('my_custom_settings');

This would be an array since the original setting was an array, so you would access the 'value' setting via the following.

$value = $mysettings[value'];

The Settings object is available as a service, so you can dependency inject it if required.

$settings = \Drupal::service('settings');
$mysettings = $settings->get('my_custom_settings');

You can also add a default value to the settings get() method in case the base setting isn't present.

$settings = \Drupal::service('settings');
$mysettings = $settings->get('my_custom_settings', ['value' => 'setting']);

Setting values in this way has a number of uses. For example, you can use this technique to store credentials that you can include into your settings.php file on remote servers. This gets around adding credentials to your source code or configuration.

Add new comment

The content of this field is kept private and will not be shown publicly.
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.