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

三世轮回 提交于 2019-12-03 17:29:28
Mike B

$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

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.

In addition to Mike B's answer, I would point that the wrong design in your code is : « we could call it wherever in our code ».

Actually, database should only be used by your Model, or the small part of your application that has to know about the database. So these classes should know there is a database, and use it as a dependency (passed through the constructor as Mike B said).

But the rest of your application should not care about a database, its should only care about the Model. Focus on refactoring and gathering all the code that access the database into Model classes.

This way, your application will have a Model layer that has a dependency : the database object/connection. And the rest of your application will use the Model, whatever happens in the Model in none of the Controller/View business.

Enjoy refactoring.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!