Reputation:
I have a project that I worked on around a year ago. I've coded various things in it and it was at a time where I was just starting out on the road to learning dependency injection.
Long story short, I've forgotten how to pass a parameter to a constructor. I've tried, although it doesn't seem to do anything. I've tried looking at the existing code for Dice but I can't work it out.
<?php declare(strict_types = 1);
$dice = new \Dice\Dice;
$configRule = [
"constructParams" => ["config_directory_here"],
];
$dice->addRule("App\Providers\Configuration", $configRule);
The class in question
<?php declare(strict_types = 1);
namespace App\Providers;
class Configuration {
private $config;
public function __construct($configDirectory) {
exit($configDirectory);
$this->config = array();
$this->loadConfig($configDirectory);
}
}
As you can see, in the constructor I have this:
exit($configDirectory);
I don't get anything back, it just continues with the code and prints the Twig template, shouldn't it at least just print an empty string even if it didn't get passed?
I've not sure if this is a problem with my dice code or my PHP itself. I have PS4 autoloading so the Configuration class should be included.
"autoload": {
"psr-4": {
"App\\": "src"
}
}
Can anyone help me here? Thanks! When adding the below code it works as expected, but I need to use a Dependency Injection Container to load the class.
$config = new \App\Providers\Config("test");
Upvotes: 0
Views: 116
Reputation: 2923
Full disclosure: I'm the author of Dice.
The reason this isn't working is because Dice never prematurely creates an object. The Configuration
object won't be created until you request an instance from the container:
$configuration = $dice->create("App\Providers\Configuration");
Upvotes: 3
Reputation: 58
The constructor is suppose to create an object and cannot return anything but the object it is attempting to create. You should never create constructors that do any job other then assigning constructor parameters to the object properties.
Upvotes: 1