Answer the question
In order to leave comments, you need to log in
Is it okay to inject a config object as a dependency into a class?
The question is not directly related to PHP in any way, I will just give examples on it.
Suppose we have a configuration object (singleton) that contains all the settings of our application:
$config = Config::getInstance();
$timezone = $config->get('timezone'); // получить настройку часового пояса
class MyService
{
/**
* @var string
*/
private $timezone;
/**
* @var string
*/
private $language;
}
public function __construct(Config $config)
{
$this->timezone = $config->get('timezone');
$this->language = $config->get('language');
}
public function __construct($timezone, $language)
{
$this->timezone = $timezone;
$this->language = $language;
}
// И, где-нибудь в boot.php:
$di->setSingleton('my-service', function () {
$config = Config::getInstance();
$timezone = $config->get('timezone');
$language = $config->get('language');
return new MyService($timezone, $language);
});
Answer the question
In order to leave comments, you need to log in
Everything is simple here if the MyService class needs everyone! data from the Config class, then pass it to the Config parameters.
If he needs only part of the data from Config, then pass the parameters separately, and if there are a lot of them, create another config that is made specifically for this class, such as "MyServiceInitalParams".
If you pass something to the class that it does not use, this will make it much more difficult to write unit tests and, in general, to read the code. Increase its connectivity.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question