简体   繁体   中英

Dependency injection in php?

I am currently building a little project with PHP whilst not using any static methods or global state.

My class' constructors currently look a little like this, I am just injecting the dependent objects upon creating an object instance.

class Something {

     public function __construct(Name\Space\Object $object, Other\Name\Space $object2) 
     {
         # Assign properties here
     }
}

In one of my application's classes I need to create new instances of various objects through the calling of its methods. Something a little like below;

class Something {

     public function getNewObject()
     {
         return new Name\Space\Object();
     }

     public function getNewObject2()
     {
         return new Name\Space\ObjectTwo();
     }
}

Is this how it should be done whilst adhering to the standard rule of dependency injection?

I am unsure how else it could be done as if I inject the object into the constructor then I will only have one instance whereas I may need many within my application?

Thanks,

I believe that functions are first class objects in PHP, so this should work:

<?php
class MyClass {
  function foo() {
    return 'foo';
  }
};

class MyOtherClass {
  function __construct($klass) {
      $this->klass = $klass;
  }

  function get_instance() {
    return new $this->klass();
  }
}

$factory = new MyOtherClass(MyClass);
$obj     = $factory->get_instance();
?>
// <h1> value should equal foo
<h1><?php echo $obj->foo();?></h1>

Edit: Tested and works.

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