I was reading a blog post when I came across this code:
<?php
include_once 'config.php';
class User
{
//Database connect
public function __construct()
{
$db = new DB_Class();
}
In the comments someone posted the following:
NEVER INITIATE db connection in the constructor
But as with all comment warriors they never give a reason why? Why is this wrong or a bad practice to do?
Constructors should not do any real work:
Work in the constructor such as: creating/initializing collaborators, communicating with other services, and logic to set up its own state removes seams needed for testing, forcing subclasses/mocks to inherit unwanted behavior. Too much work in the constructor prevents instantiation or altering collaborators in the test.
Instead, use Dependency Injection and pass any collaborators to the constructor. This will create code that is easier to test. When you new
something in the ctor, it is much more difficult to mock/stub that with a Test Double.
Also, by injecting collaborators, you are making it easier to swap out collaborators with different implementations, thus reducing coupling, fostering code reuse and coding towards interfaces instead of concrete implementations.
Passing instance of the Data Base to the constructor called "dependency injection". This is done for decoupling of objects, meaning lowering the dependencies between objects. One of the benefits of decoupling is greater flexibility in the system, easier maintenance, and writing unit tests.
But you can enjoy all of this benefits mainly if you build your software using design patterns, practicing test driven development, and well defined architecture - as for example practiced in domain driven design.
But if you only starting to explore the OOP way of developing software or just starting to learn programming in general - maybe you shouldn't bother yourself with these kind of questions just yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With