OOP dependencies: attachment and registry dependency

I know some OOPs and have read this and this, but I am not a hardcore OOP guy and have no formal training and cannot break down why something should use dependency injection or not, and may not be able to identify all the dependencies in the design, therefore my question.

Answering the question here about SO ( Using an Object in the Methods of Other Objects ), I began to doubt myself. As for addictions, is one of them better or worse, or are both acceptable? Any design restrictions?

I read and understood both, but never met a comparison. Why is it better to use it in design, etc.

Dependency Injection:

class myClass {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }
}

Registry (maybe something else):

class myClass {
    private $db;

    public function __construct() {
        $this->db = Registry::get('db');
    }
}
+4
3

- . () , , . inversion of control.

, , .

DI container, , . ():

  • args
  • ( , )
  • setter
  • ...
+5

.

, (Dependency Injection) . , , db , , , mock db myClass - .

() , myClass db, Registry, , db. , , , , - .

+6

, .

:

  • B, A B
  • (, Registry, ..) . . , .
  • . " "

, - , :

public class ClassA
{
 // declares the dependency in the constructor

 public function ClassA( dependency1:String )
 {}
}

// and the dependency is created while instantiating the object
var objA:ClassA = new ClassA("Hello World");

public class ClassA
{
 // declares the dependency as a public property
 public var helloStr:String;
}

var obj1:ClassA = new ClassA();

// dependency is fulfilled by setting a public property after instantiation:
obj1.helloStr = "The Zen Master";
+3

Source: https://habr.com/ru/post/1529105/


All Articles