简体   繁体   English

PHP ::存储数据库连接与静态实例化

[英]PHP :: Storing a database connection v. static instantiation

Which of these approaches is more efficient (or proficient) in PHP? 以下哪种方法在PHP中更有效(或精通)?

class Amazing {
    protected $db;

    public function __construct () {
         $this->db = new Database::getInstance();
    }

    public function do ($blah) {
         $this->db->doInsert($blah);
    }

    public function again ($blah) {
         $this->db->doUpdate($blah);
    }
}

OR: 要么:

class Less_Amazing {

    public function do ($blah) {
         $db = new Database::getInstance();
         $db->doInsert($blah)
    }

    public function again ($blah) {
         $db = new Database::getInstance();
         $db->doUpdate($blah)
    }
}

A pint of beer is riding on the answer. 一品脱啤酒就在答案上。

I would suggest using dependency injection for such cases. 我建议在这种情况下使用依赖注入。 Your class should be as less dependent on other classes as possible. 您的班级应尽可能少依赖其他班级。 Any dependency should be provided to it while building the object through dependency injection. 通过依赖项注入构建对象时,应提供任何依赖项。 Each class should follow the Single Responsibility principle, ie, each class should have a single responsibility. 每个班级应遵循“单一责任”原则,即每个班级应负有单一责任。 Dependency injection is enabled by inversion of control. 通过控制反转可以启用依赖项注入。 That means the class Amazing does not have to create an instance of database connection. 这意味着Amazing类不必创建数据库连接的实例。 A database connection object is provided to it through constructor injection and all it has to do is do its 'amazing work':) 通过构造函数注入为它提供了一个数据库连接对象,而它要做的就是完成其“惊人的工作” :)

$db = new Database::getInstance();
$amazing = new Amazing($db);

class Amazing {
    protected $db;

    public function __construct ($db) {
         $this->db = $db;
    }

    public function do ($blah) {
         $this->db->doInsert($blah);
    }

    public function again ($blah) {
         $this->db->doUpdate($blah);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM