mnapoli/PHP-DI — pull request #134 by jflitton (2013-12-05 00:04:30+00:00)
Title: Name-based constructor parameter lookup

I'm using reflection to inject parameters into constructors and encountered a situation where I had a constructor such as:

/**
* @param Class1 $param1
* @param Class2 $param2
* @param Class3 $param3
* @param String $param4
function __construct(Class1 $param1, Class2 $param2, Class3 $param3, $param4)

So the first three parameters are automatically satisfied properly by PHP-DI, but the fourth could not be satisfied, causing a DefinitionException: "The parameter 'param4' of the constructor of 'SomeClass' has no type defined or guessable"

I was already setting a value in the container as follows: $container->set('param4', 'some value that I want injected');

I eventually realized that I could do something like:
$container->set('SomeClass')->withConstructor(array(
'param1' => 'Class1',
'param2' => 'Class2',
'param3' => 'Class3',
'param4' => 'param4'));

But since my actual constructor takes 8 arguments, this solution gets pretty verbose and is another bit of configuration data to maintain.

As a result, I changed Factory->injectConstructor so that in cases where there is no EntryName for the parameter, it checks the container for an item matching the parameter name. If it fails to find one, it checks for a default value as it did before. Finally if there is no default value, it throws the same DefinitionException as before. I've re-worked the tests to exercise this new path.

Is this something you'd be interested in including?