I'm self taught & unsure on how to do this, need to access a single instance of my config class, everywhere. Could use a DIC to inject everywhere, but I want it to work dynamically.
I could make the class static, but is that the answer? A DIC could be useless here even. I would be extreemly grateful if someone could give me some advice here. Looking for a clean way, not dirty.
Here is my current setup for injecting into controllers, for things like templating.
$controllerRule = [
"constructParams" => [$dice->create("App\Providers\Template")],
"shared" => true,
];
$dice->addRule("App\Controllers\Frontend\LandingController", $controllerRule);
Here is how I'm currently creating the instance of Config, with my DIC.
$configRule = [
"constructParams" => ["example"],
"shared" => true,
];
$dice->addRule("App\Providers\Configuration", $configRule);
Best practice? Don't.
Ask yourself this: Does a class that needs the Config instance require access to all configuration options?
Instead of:
class HomeController {
private $numberOfItemsShown;
public function __construct(Config $config) {
$this->numberOfItemsShown = $config->get('homepage.number_of_items');
}
}
Do this:
class HomeController {
private $numberOfItemsShown;
public function __construct(int $numberOfItemsShown) {
$this->numberOfItemsShown = $numberOfItemsShown;
}
}
If a class requires many constructor params, you have a couple of options.
A general rule of thumb is that a class should ask for its configuration, not retrieve it.