简体   繁体   中英

php dependency injection with parameter

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

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:

  1. Use . instead of + to concatenate strings: return "See you later on other class with my parameter " . $this->param; return "See you later on other class with my parameter " . $this->param;

  2. Need to return something from the apple() method: return $this->objects->go();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM