Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP avoid static classes to avoid dependencies, but I need to use global everywhere

Many times I heard to avoid static classes because they will insert dependencies that will render your code unusable in other projects, and will not allow to unit test it.

Let's say we have a typical class DB to access the Data Base, if such class is static we could call it wherever in our code:

DB::execQuery(...);

but this creates dependencies, so let's make the DB class NOT static, in such case we would have somewhere in our code:

$db = new DB();

and then we could call in our code

$db->execQuery(...);

But now when using the $db inside a function we need each time to first declare it like this

global $db;

Is there a way to workaround this?

One way could be to inject the $db object in the class that uses it, but I would have to inject it in all classes that use it, that's ridicolous, a static class would be much quicker to work with and less code to write. Am I missing something?!

like image 787
Marco Demaio Avatar asked Dec 12 '25 15:12

Marco Demaio


1 Answers

$db could be injected upon instantiation into a property, then you would only need to access this property instead of passing it around to each method.

class MyClass {
  protected $_db; // DB Connection
  public function __construct($db) {
    $this->_db = $db;
  }

  public function foo() {
    $this->_db->query('...');
  }

}

Beyond that, you can look into having a service-container (aka dependency-injection container) that trys to act like a global variable but solves some of the testing issues. Take a look at some of these related questions

  • If Singletons are bad then why is a Service Container good?
  • Is it good practice to have DI container replace a global $registry object?

Having a DI container lets you use static methods in your classes like DI_Container::get('db'). It looks a lot like global or some of the other static calls.. but in this case DI_Container contains special methods that allow for extra actions to be taken during testing and other circumstances.. eliminating some of the 'evilness' of global.

like image 172
Mike B Avatar answered Dec 15 '25 07:12

Mike B