Ok, so the core problem is to create create command handler objects generically, but constructor injection enforces individual parameters for each command handler.
This can be easily solved by separating the construction process for the chain from the actual constructor call utilizing a corresponding factory class for each of your handler classes. Each factory constructor stays parameterless, but inside each factory the handler objects will be constructed with the required services injected.
By using using a strict naming scheme like FirstHandlerFactory
for FirstHandler
, SecondHandlerFactory
for SecondHandler
etc, the resulting code will then look like
foreach ( $modulesQueue as $moduleName ) {
$factoryName = "extensions\\".$moduleName."Factory";
$startModule->setSuccessor((new $factoryName())->buildModule());
}
(Note I did not fix that this code does not set up a chain of command, to keep things simple, but I am sure you get the idea.)
The buildModule
function then may look like this
class FirstHandlerFactory
{
function buildModule()
{
return new FirstHandler(/* provide the individual services here */);
}
}
In your unit tests, you will be able to create your handler objects just with mock services injected, as required for the specific test, without using the factories.
This solution does neither require a DI framework, nor some convoluted reflection mechanism.