Stanley Ngumo Stanley Ngumo - 2 months ago 8
PHP Question

Trouble injecting defined parameters into constructor using PHP-DI

This may seen rudimentary but I cant seem to directly inject any parameters into my class constructor without using annotations. Below is definition made and the class called

$shell->set('root','[Root Definition Here]');

$shell->make('Namespace\To\Product');

Class Product{

public function __construct($root){
//coding continues here
}
}


But I keep getting this error


Uncaught exception 'Exception' with message 'Entry
"Namespace\To\Product" cannot be resolved:
Parameter $root of __construct() has no value defined or guessable


However this issue will be resolved if I use annotations. But I really want not to resort to annotations each time I'm injecting parameters.

Whats the issue here?

Thanks

Answer

PHP-DI injects using the type-hints, not the parameter names. So it would work if $root had a type-hint (e.g. Foo\Bar $root), but as it is now it can't work.

You have to define the parameter manually:

$container->set(
    'Namespace\To\Product',
    DI\object()->constructor(DI\get('root')
);