Reputation: 677
Hello I am using php dependency-injection in this script below .Everything works when the injected object or class has no constructor. But the issue here is that when the injected class get a constructor function along with parameter , injection fails .I would like to know how to deal with this case.
require 'vendor/autoload.php';
class useMe {
private $param ;
function __construct($param) {
$this->param = $param ;
}
public function go() {
return "See you later on other class with my parameter " . $this->param;
}
} // end of useMe Class
class needInjection {
private $objects ;
public function __construct(useMe $objects) {
$this->objects = $objects ;
}
public function apple() {
return $this->objects->go();
}
} // end of needInjection
/** Implementing now injection **/
$container = DI\ContainerBuilder::buildDevContainer();
// adding needInjection class dependency
$needInjection = $container->get('needInjection');
echo $needInjection->apple() ; // this fails due to parameter passed to the constructor function of useMe class
NOTE : This example has been simplified for understanding purpose
Upvotes: 3
Views: 4517
Reputation: 1520
You need to add a definition so that PHP-DI knows how to construct your useMe
object (tested under php 5.6):
$builder = new \DI\ContainerBuilder();
$builder->addDefinitions([
'useMe' => function () {
return new useMe('value_of_param');
},
]);
$container = $builder->build();
This is explained in the PHP-DI manual in the section about PHP Definitions: http://php-di.org/doc/php-definitions.html
A couple of other things you might need to change:
Use .
instead of +
to concatenate strings: return "See you
later on other class with my parameter " . $this->param;
Need to return
something from the apple()
method: return
$this->objects->go();
Upvotes: 1