Continuing from our previous lesson on using config.factory
to save module settings, this lesson will teach you how to retrieve those configuration values programmatically. This ability is essential for developing modules that need to adapt based on user-configured options.
Why Retrieve Configuration Values Programmatically?
Accessing configuration values programmatically allows your module to dynamically respond to environment changes. By querying your settings at runtime, you can:
- Apply Conditional Logic: Adjust module behavior based on configuration settings.
- Integrate with External Services: Retrieve API keys or other necessary information to communicate with third-party services.
- Improve User Experience: Ensure your application reflects the latest configuration settings efficiently.
Example Scenario: Using Weather Module Settings
Let's continue with our weather module example. We will show how to retrieve the API key and default location settings and use them to request weather information dynamically.
Step 1: Inject the Config.factory Service
To access configuration data, you'll need to inject the config.factory
service into your class. This follows the dependency injection pattern we employed in previous lessons.
// weather_module/src/Service/WeatherDataRetriever.php
namespace Drupal\weather_module\Service;
use Drupal\Core\Config\ConfigFactoryInterface;
use GuzzleHttp\ClientInterface;
class WeatherDataRetriever {
protected $configFactory;
protected $httpClient;
public function __construct(ConfigFactoryInterface $config_factory, ClientInterface $http_client) {
$this->configFactory = $config_factory;
$this->httpClient = $http_client;
}
public function fetchWeatherData() {
// Retrieve the module configuration
$config = $this->configFactory->get('weather_module.settings');
$api_key = $config->get('api_key');
$default_location = $config->get('default_location');
// Build request to the weather API
$request_url = "http://api.weatherapi.com/v1/current.json?key={$api_key}&q={$default_location}";
$response = $this->httpClient->get($request_url);
return json_decode($response->getBody(), TRUE);
}
}
Step 2: Define the Service in Your Module
Add your newly created service to the module's service definition file to ensure Drupal recognizes it and can manage dependency injection.
// weather_module.services.yml
services:
weather_module.weather_data_retriever:
class: 'Drupal\weather_module\Service\WeatherDataRetriever'
arguments: ['@config.factory', '@http_client']
Step 3: Utilize the Configuration Data
With your service set up, you can now use the retrieved configuration data elsewhere in your module, such as a controller or block, to fetch and display weather data.
// weather_module/src/Controller/WeatherDisplayController.php
namespace Drupal\weather_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\weather_module\Service\WeatherDataRetriever;
class WeatherDisplayController extends ControllerBase {
protected $weatherDataRetriever;
public function __construct(WeatherDataRetriever $weather_data_retriever) {
$this->weatherDataRetriever = $weather_data_retriever;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('weather_module.weather_data_retriever')
);
}
public function display() {
$weather_data = $this->weatherDataRetriever->fetchWeatherData();
$build = [
'#markup' => $this->t('The current temperature in @location is @temp°C.',
['@location' => $weather_data['location']['name'], '@temp' => $weather_data['current']['temp_c']]),
];
return $build;
}
}
Conclusion and Next Steps
In this lesson, you learned how to retrieve configuration values programmatically using the config.factory
service. This knowledge enables your module to be highly dynamic and responsive to changes in configuration settings.
In the next lesson, we will discuss "Including default config in config/install", ensuring your module ships with useful default settings that users can build upon.
Keep coding, and I'll see you in the next module development tutorial!