Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP why is it not good to initiate a db connect in a construct? [closed]

Tags:

object

php

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?

like image 646
twigg Avatar asked Jan 03 '13 12:01

twigg


2 Answers

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.

like image 70
Gordon Avatar answered Oct 14 '22 02:10

Gordon


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.

like image 26
Vlad Lyga Avatar answered Oct 14 '22 01:10

Vlad Lyga