3

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

2
  • 1
    what is $aparam in the useMe class? Should be $this->param = $param; (no space either, before semicolon) Commented Jan 11, 2018 at 23:38
  • I highly recommend to not edit the initial post with the corrections, based on comments... it might lead others astray --- especially if you are still having problems Commented Jan 12, 2018 at 2:26

1 Answer 1

1

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;

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks @astrangeloop ofr this answer , it works now...therefore I declare this question resolved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.