如何在我的整个应用程序中只实例化一次PDO,而不是每次我想进行查询?

时间:2014-12-08 14:08:10

标签: php mysql function pdo

目前,每当我想创建一个新函数来创建不同类型的查询时,我都必须重新实例化PDO ...更进一步,如果我创建了另一个类,我可以使用'类B扩展A',而不必创建一个全新的构造函数?

class Site {
    var $driver;
    var $host;
    var $dbname;
    var $user;
    var $pass;

    public function __construct($driver, $host, $dbname, $user, $pass) {
        $this->driver = $driver;
        $this->host = $host;
        $this->dbname = $dbname;
        $this->user = $user;
        $this->pass = $pass;        
    }
    public function jazz() {
        $d = new PDO("$this->driver:host=$this->host;dbname=$this->dbname", "$this->user","$this->pass");
        $d->query('SELECT name, price FROM products ORDER BY id ASC');
    }
    public function buzz() {
        $c = new PDO("$this->driver:host=$this->host;dbname=$this->dbname", "$this->user","$this->pass");
        $c->query('SELECT name, age FROM clients ORDER BY name ASC');
    }
}

2 个答案:

答案 0 :(得分:1)

只需在构造函数中设置连接,然后就可以在类函数中使用它

class Site {
    var $driver;
    var $host;
    var $dbname;
    var $user;
    var $pass;
    private $conn;

    public function __construct($driver, $host, $dbname, $user, $pass) {
        $this->driver = $driver;
        $this->host = $host;
        $this->dbname = $dbname;
        $this->user = $user;
        $this->pass = $pass;        
        $this->conn=  new PDO("$this->driver:host=$this->host;dbname=$this->dbname", "$this->user","$this->pass");
    }

    public function jazz() {
        $this->conn->query('SELECT name, price FROM products ORDER BY id ASC');
    }

    public function buzz() {

        $this->conn->query('SELECT name, age FROM clients ORDER BY name ASC');
    }
}

答案 1 :(得分:1)

class Site {

    protected $db;

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

    public function jazz() {
        $this->db->query(...);
    }

}

$db   = new PDO(...);
$site = new Site($db);
$site->jazz();

它被称为依赖注入