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:
Instead, use Dependency Injection and pass any collaborators to the constructor. This will create code that is easier to test. When you
newsomething 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.