简体   繁体   中英

PHP :: Storing a database connection v. static instantiation

Which of these approaches is more efficient (or proficient) in 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. 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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