PHP避免使用带有PDO连接的全局$数据库

时间:2014-07-24 10:19:09

标签: php pdo global

我在下面有这个代码。我想要的是避免使用全球$ db ,因为我听说过它的不良做法,而且我正在寻找更强大/更好实现的功能。 / p>

connection.php

<?php
try {
    $db = new PDO('mysql:host=127.0.0.1;dbname=blop', 'blop', 'root');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    $error = $e->getMessage();
    echo $error;
}
?>

admin.php的

<?php
class Admin {

    public function fetch_data() {
        global $db;

        $sql = "SELECT * FROM `people` ORDER BY `id` DESC";
        $result = $db->query($sql);

        return $result;
    }

    public function fetch_row_count() {
        global $db;

        $sql = "SELECT * FROM `people`";
        $result = $db->query($sql);
        $num_rows = $result->rowCount();

        return $num_rows;
    }

    public function deleteAll() {
        global $db;

        $deleteAll = $db->prepare("DELETE FROM `people`");
        $deleteAll->execute();
    }

    public function deleteData($id) {
        global $db;

        $id = $_POST['id'];
        $deleteData = $db->prepare("DELETE FROM `people` WHERE `id` = '$id'");
        $deleteData->execute();
    }
}
?>

2 个答案:

答案 0 :(得分:2)

依赖注入是指将类所需的所有依赖项(在本例中为PDO)传递给类。下面是一个使用构造函数注入(我们将数据库传入构造函数)的示例。在实例化对象时,您需要像$admin = new Admin($db);而不是$admin = new Admin();

那样执行此操作

另请注意,在方法deleteData中应删除行$id = $_POST['id'];,因为它不仅使用另一个依赖项(post请求),而且还会覆盖传入方法的$ id,使方法签名毫无意义。

希望这有帮助。

class Admin {

    protected $db;

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

    public function fetch_data() {

        $sql = "SELECT * FROM `people` ORDER BY `id` DESC";
        $result = $this->db->query($sql);

        return $result;
    }

    public function fetch_row_count() {

        $sql = "SELECT * FROM `people`";
        $result = $this->db->query($sql);
        $num_rows = $result->rowCount();

        return $num_rows;
    }

    public function deleteAll() {

        $deleteAll = $this->db->prepare("DELETE FROM `people`");
        $deleteAll->execute();
    }

    public function deleteData($id) {

        $deleteData = $this->db->prepare("DELETE FROM `people` WHERE `id` = '$id'");
        $deleteData->execute();
    }
}

答案 1 :(得分:0)

介绍依赖注入

class Admin {

    protected $db;

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

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

    ...

}

$pdo   = new PDO(...);
$admin = new Admin($pdo);
$admin->fetch_data();

非常简单,真的。您只需所有外部依赖项显式传递到需要它的类中。