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'); } }
- . () , , . inversion of control.
inversion of control
, , .
DI container, , . ():
DI container
.
, (Dependency Injection) . , , db , , , mock db myClass - .
db
myClass
() , myClass db, Registry, , db. , , , , - .
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";
Source: https://habr.com/ru/post/1529105/More articles:Dependent variable labels in asterisk tables - rnosql / dynamodb hash and usage range - amazon-web-servicesCCTableView with cocos2d 3.0 - cocos2d-iphoneColor cluster of sheets based on icons inside - javascriptSpritekit adds sound effect - iosUsing an object in methods of other objects - methodsApplication output to Synthesizer.Speak - System.Speech.dll - Non Microsoft Voices - c #Make jar run in 32bit jre - javaPrevious Java elements in ArrayList / List are replaced when the next element changes - javaMacOS code signing in JDK7 bundle on Mavericks 10.9.1 - javaAll Articles