Are injectable classes allowed to have constructor parameters in DI?
- by Songo
Given the following code:
class ClientClass{
public function print(){
//some code to calculate $inputString
$parser= new Parser($inputString);
$result= $parser->parse();
}
}
class Parser{
private $inputString;
public __construct($inputString){
$this->inputString=$inputString;
}
public function parse(){
//some code
}
}
Now the ClientClass has dependency on class Parser. However, if I wanted to use Dependency Injection for unit testing it would cause a problem because now I can't send the input string to the parser constructor like before as its calculated inside ClientCalss itself:
class ClientClass{
private $parser;
public __construct(Parser $parser){
$this->parser=$parser;
}
public function print(){
//some code to calculate $inputString
$result= $this->parser->parse(); //--> will throw an exception since no string was provided
}
}
The only solution I found was to modify all my classes that took parameters in their constructors to utilize Setters instead (example: setInputString()).
However, I think there might be a better solution than this because sometimes modifying existing classes can cause much harm than benefit.
So,
Are injectable classes not allowed to have input parameters?
If a class must take input parameters in its constructor, what would be the way to inject it properly?
UPDATE
Just for clarification, the problem happens when in my production code I decide to do this:
$clientClass= new ClientClass(new Parser($inputString));//--->I have no way to predict $inputString as it is calculated inside `ClientClass` itself.
UPDATE 2
Again for clarification, I'm trying to find a general solution to the problem not for this example code only because some of my classes have 2, 3 or 4 parameters in their constructors not only one.