依存性注入を使用してカスタムサービスクラスの構成設定を確認するにはどうすればよいですか?
カスタムサービスクラスで、構成設定を確認する必要があります。
ここに記載されているように、これを使用してこれを行うことができ\Drupal::config(static::SETTINGS)
ます。https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms
しかし、Coderは文句を言います:
警告|
\Drupal
クラスでは呼び出しを避け、代わりに依存性注入を使用する必要があります
ここにどのようなサービスを注入する必要がありますか?
不変の構成値を確認するだけでよく、は必要ないと思いますConfigFactory
。
より詳しい情報:
ConfigFactoryInterface
他の多くのサービスで使用したパターンを使用してを挿入しようとすると、次のエラーが発生します。
エラー:未定義のメソッドの呼び出し
Drupal\my_custom_module\Api\DataPartner::config()
でDrupal\my_custom_module\Api\DataPartner->hasDebugPermission()
hasDebugPermission()
メソッドのコードは次のようになります。
/**
* Private function to control whether displaying debug info is permitted.
*
* @return bool
* TRUE if debugging is permitted for current user in current environment.
*/
private function hasDebugPermission() {
$config = $this->config(static::SETTINGS);
$result = DATA_PARTNER_FORMS_DEBUG && $config->get('display_debugging_info')
&& $this->account->hasPermission('debug forms'); return $result;
}
そして私はstatic::SETTINGS
このように宣言しました:
/**
* Config settings.
*
* @var string
*/
private const SETTINGS = 'my_custom_module.settings';
の呼び出しは$this->account->hasPermission()
注入後に正常に機能します\Drupal\Core\Session\AccountInterface
が、への呼び出し$this->config('my_custom_module.settings')->get('display_debugging_info')
は注入後に機能しません\Drupal\Core\Config\ConfigFactoryInterface
。
回答
必ず注入してconfig.factory
から、以下を使用する必要があります。
$this->config
->get('my_custom_module.settings')
->get('display_debugging_info');
Drupal :: config()が次のようになっていることがわかります。
public static function config($name) {
return static::getContainer()
->get('config.factory')
->get($name);
}
したがって、サービスを注入した後、次のようになります\Drupal::config('my_custom_module.settings')
。
$this->config->get('my_custom_module.settings');