I am reading about design patterns in PHP and I keep seeing the following syntax, for example
$newClass = new myClass(new myOtherClass());
I guess that this passes some kind of a myOtherClass
reference inside myClass
, so here
class myClass{
private $myOtherClass;
public function __construct(myOtherClass $myOtherClass) {
$this->myOtherClass= $myOtherClass;
}
public function myClassMethod($var) {
$this->myOtherClass->methodOfMyOtherClass($var);
}
}
the construct refers to myOtherClass
and I can use the methodOfMyOtherClass
of myOtherClass
from the myClass
myClassMethod
, like so $newClass->myClassMethod('a value here');
My questions are :
What is the name of that practice?
Did I got the concept right?
Where can I read more about it?
(first time I saw this syntax is here , this is where I also based my code for this question)
What is the name of that practice?
Typically this is called Dependency Injection
. myClass
required myOtherClass
in order to properly execute it's methods, so myOtherClass
is a dependency of myClass
. Read more here .
Did I got the concept right?
It looks like you have the concept right. At least based on your sample, you are using it correctly.
Where can I read more about it?
If you want to read more about Dependency Injection only, I recommend this . In general, the principles taught by the 12 Factor App are very good and are worth reading about. 12 Factor App .
Some good books worth reading along these lines:
Clean Code
Patterns for Enterprise Architecture
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.