Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Last active July 22, 2023 16:28
Show Gist options
  • Save JeffTomlinson/b733eb9224dba07a459cd09f3df56b93 to your computer and use it in GitHub Desktop.
Save JeffTomlinson/b733eb9224dba07a459cd09f3df56b93 to your computer and use it in GitHub Desktop.
Drupal 8 Configuration Dependency Injection
<?php
/**
* Get my setting.
*/
function get_my_setting() {
return /Drupal::service('my_module.my_service')->getMySetting();
}
services:
my_module.my_service:
class: Drupal\my_module\Services\MyService
arguments:
- '@config.factory'
# /my_module/config/install/
my_setting: "Foo"
<?php
namespace Drupal\my_module\Services;
use Drupal\Core\Config\ConfigFactory;
/**
* Class MyService.
*
* @package Drupal\my_module\Services
*/
class MyService {
/**
* Configuration Factory.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;
/**
* Constructor.
*/
public function __construct(ConfigFactory $configFactory) {
$this->configFactory = $configFactory;
}
/**
* Gets my setting.
*/
public function getMySetting() {
$config = $this->configFactory->get('my_module.settings');
return $config->get('my_setting');
}
}
@twfahey1
Copy link

Thank you for posting

@scottalan
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment