How do I best decouple two classes but still have them depend on each other?
I have constructor arguments with type hinting:
public function __construct(\namespace\Interface1 $class1,
\namespace\Interface2 $class2,
\other\namespace\Abstract1 $class3){
But is this as tightly coupled as, say:
new \namespace\Class1();
Any other methods welcome.
Using an interface means you are decoupled from the implementations.
You cannot use another component (ie a dependency) without being coupled to at least something. The question is how to minimize this coupling:
In the end, that's about choosing the solution that involves the less coupling.
An alternative to this would be to use events: your class could raise events, and have dependencies listen to those events. That way, your class is only coupled to an interface of an EventManager.
But the event solution doesn't really fit every use case: you have no guarantee that anyone actually registered to the event, and actually did something on that event. And you can't get the result back like you could if you just called a method.
Conclusion: using an interface like you do is good, there is no problem here. :)
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.