after reading this question i wonder if someone can help me understand how to implement correctly Dependency Injection with these PHP Classes:
class DBClass
-
Yes. You are now injecting the dependencies through the constructor which provides for less coupling. You can now more easily swap out these dependencies, e.g. when UnitTesting you can replace them with Mocks.
You have still some coupling though by using the concrete DBClass as a TypeHint instead of an interface. So when you would want to use a different DBClass, it would have to be named DBClass. You could achieve more loose coupling by coding against an interface that the concrete classes have to implement instead.
To create only single instances of a class (as asked in the comments), you could either use a Singleton (like Kevin Peno suggested) or a Factory to create and keep track of if the instance has been created yet. Or use a DI Service Container, which is similar to a Factory, yet not the same thing. It creates and manages objects for you.
The Symfony Components library has a Dependency Injection Container with excellent documentation and introduction to the topic on how to further enhance DI this with Service Containers. The containers can also be used to limit instances. Check it out.
讨论(0)
- 热议问题