A
A
Alexander2016-05-04 20:29:15
Software design
Alexander, 2016-05-04 20:29:15

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'); // получить настройку часового пояса

Also, there is a service class that has some dependencies that are taken from the configuration:
class MyService
{
    /**
     * @var string
     */
    private $timezone;

    /**
     * @var string
     */
    private $language;
}

This service will be created using a DI container and will exist in a single instance (it will be a singleton). There are two options for initializing the service properties:
1. We pass the entire configuration object to the class constructor and get the necessary properties inside the constructor:
public function __construct(Config $config)
{
    $this->timezone = $config->get('timezone');
    $this->language = $config->get('language');
}

2. We pass ready-made parameter values ​​to the class constructor, having previously received them from the configuration at the DI container settings level:
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);
});

It is clear that in the first case, the class begins to depend on the whole configuration object, but, on the other hand, the amount of code related to the initialization of objects in the DI container is greatly reduced if there are a lot of settings.
I saw an article on this topic on Habré, but I can not find it, unfortunately.
Which method seems preferable to you, and, most importantly, why ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2016-05-05
@Sing303

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 question

Ask a Question

731 491 924 answers to any question