Drupal's config factory for reading settings in services
Drupal's Config Factory gives custom services a supported way to read configuration without embedding values in PHP code. A service can request a named configuration collection, inspect a setting and apply it to an API request, scheduled task or content workflow. This keeps behaviour adjustable by site builders while allowing the underlying service to remain reusable.
Consider a service that calls an Australian freight-rate provider. The provider URL, request timeout and enabled transport methods belong in Drupal configuration rather than class properties. The service receives the configuration factory through dependency injection, retrieves those values when needed and avoids duplicating operational settings across controllers, commands and plugins.
Injecting the factory also makes the dependency visible to other developers and test frameworks. Instead of reaching for a global helper, a class declares exactly which configuration service it requires. Drupal's unit and kernel testing tools can then provide predictable values without making live requests to an external system.
Configuration is only one part of a site's setup. Exportable settings belong in Drupal configuration, while credentials and machine-specific values often belong in settings.php, environment variables or a secrets manager. The pattern works consistently across Drupal 9, 10 and 11 when these responsibilities remain separate.
Where the configuration factory belongs
Drupal registers config.factory in its service container. It implements ConfigFactoryInterface, and its get() method returns an immutable configuration collection identified by a machine name such as mysite.settings. The collection can contain strings, numbers, booleans and nested arrays defined in YAML.
| Access method | Dependency style | Configuration source | Appropriate use |
|---|---|---|---|
config.factory injection |
Explicit constructor dependency | Active Drupal configuration | Custom services and automated tests |
config() helper |
Implicit global dependency | Active Drupal configuration | Legacy code and short administrative scripts |
Settings::get() |
Static site setting | Values from settings.php |
Credentials and deployment-specific values |
A configuration object normally starts in a module's config/install directory:
# config/install/mysite.settings.yml
api_base_url: 'https://api.example.com.au'
request_timeout: 10
features:
live_lookup: true
Those files provide defaults when the module is installed. Later changes are stored as active configuration, which can differ between development, staging and production sites. The configuration factory reads that active collection rather than reading the YAML file directly.
Injecting the factory into a custom service
A module can define its service in mysite.services.yml. The service container creates the class and supplies config.factory as its constructor argument.
# mysite.services.yml
services:
mysite.settings_reader:
class: Drupal\mysite\SettingsReader
arguments:
- '@config.factory'
The PHP class type-hints the interface rather than the concrete implementation. That keeps the class independent of Drupal's internal service implementation and provides a clear contract for automated tests.
<?php
namespace Drupal\mysite;
use Drupal\Core\Config\ConfigFactoryInterface;
class SettingsReader {
protected ConfigFactoryInterface $configFactory;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public function getBaseUrl(): string {
$settings = $this->configFactory->get('mysite.settings');
return (string) $settings->get('api_base_url');
}
}
After changing a service definition, rebuild Drupal's caches so the compiled container includes the update. Autowiring can remove the explicit argument where the project already relies on interface aliases, but an explicit @config.factory argument remains easy to understand and works across a wide range of Drupal projects.
Reading configuration values safely
The get() method on a configuration collection returns the requested value, but it can also return NULL when the key is absent. The has() method distinguishes a missing key from a deliberately stored false value, which matters for feature switches and optional integrations.
$settings = $this->configFactory->get('mysite.settings');
if (!$settings->has('api_base_url')) {
throw new \RuntimeException('The mysite.api_base_url setting is missing.');
}
$base_url = (string) $settings->get('api_base_url');
Values should be validated at the service boundary. YAML can parse true, 10 and '10' differently, while get() returns a mixed value. Casting the result to the required type gives the rest of the class a predictable contract. Empty strings and null values require separate handling if they are meaningful to the integration.
Nested keys use dot notation, such as features.live_lookup. Calling getRawData() is appropriate when the complete array is needed, although reading individual keys is usually clearer. Because a configuration object is immutable, services should treat it as a source of values rather than attempting to modify it during a request.
Handling overrides and deployment differences
The factory reads active Drupal configuration, so developers should distinguish configuration defaults from values that are actually deployed. drush config:export writes the active collection into the site's config directory, and drush config:import loads exported configuration into another environment. This is the normal mechanism for moving a setting such as a timeout or feature flag between environments.
Environment-specific values need a controlled deployment strategy. Configuration splitting can separate shared settings from site-specific ones, preventing a local API URL from being copied to production. A configuration override module can also change values at runtime, so developers should know whether a project uses that mechanism before diagnosing a discrepancy.
Secrets should not be exported as ordinary Drupal configuration. A configuration export can be committed, downloaded or included in a deployment package, making it unsuitable for an API key or password. A deployment-specific setting can instead be defined in settings.php:
$settings['mysite_api_key'] = getenv('MYSITE_API_KEY') ?: 'development-key';
The config.factory remains appropriate for non-secret operational settings, while Settings::get() handles values deliberately placed in settings.php. After an import or override change, rebuilding caches ensures that a web process receives the current container and configuration state.
Configuration patterns for Australian websites
Australian sites often need values such as AUD, Australian English formatting and a GST-inclusive pricing rule. These can be stored in configuration and consumed by a commerce or display service. A retailer in Melbourne and a wholesaler in Brisbane can share one module while using different tax labels, support addresses or ordering settings. Formatting remains the responsibility of the relevant currency, address and text-formatting utilities.
Time zones require particular care. Australia/Sydney and Australia/Adelaide are safer than fixed offsets because daylight-saving rules change throughout the year. Adelaide also operates on a half-hour offset from UTC. Store an IANA time-zone identifier and let Drupal or PHP calculate local time. Public holidays vary by state and are revised regularly, so a stable calendar service is more reliable than a collection of hard-coded dates in configuration.
Privacy settings also affect integrations. Under the Privacy Act 1988 and the Australian Privacy Principles, configuration should identify an endpoint or feature flag without containing customer names, email addresses, IP addresses or other personal information. Marketing integrations may also need to account for the Spam Act 2003 and Australian Consumer Law requirements. A business can use a .com.au domain, but the domain choice does not replace the need for appropriate consent, retention and disclosure controls.
Testing and diagnosing configuration problems
A kernel test can write an active value and then retrieve the service from the container. This verifies both the configuration key and the service's reading logic without contacting the external provider.
$this->config('mysite.settings')
->set('api_base_url', 'https://api.example.com.au')
->save();
$reader = $this->container->get('mysite.settings_reader');
$this->assertSame(
'https://api.example.com.au',
$reader->getBaseUrl()
);
Services should normally read configuration when a method runs rather than caching values permanently in the constructor. Otherwise, a configuration save during a test or long-running process may leave the service with stale information. Unit tests can mock ConfigFactoryInterface, while kernel tests are useful when the complete configuration system is part of the behaviour under examination.
Several commands help locate an unexpected value:
drush config:get mysite.settings api_base_url
drush config:status
drush cache:rebuild
drush php:eval "\Drupal::config('mysite.settings')->getRawData();"
A missing value usually indicates a misspelled collection or key, configuration that was never imported or a service using the wrong environment. Rebuilding the container is essential after changing service arguments or YAML definitions. The configuration factory provides reliable access, but the collection name, deployment workflow and cache state must still match the site being diagnosed.