将PDO与其他类一起使用


Using PDO with other classes

我一直在强迫自己进入更多的OOP。直到现在我都讨厌这一切。当我在另一个类中的PDO中使用一些简单的prepare语句作为方法时,它永远不会起作用。我通过做显而易见的事情来解决这个问题:将PDO对象全局化到方法中。它可以工作,而且可以做我想要的事情——但如果我有很多来自不同类的方法,添加"global$db;"作为所有函数/方法的第一行,这似乎很乏味。有没有一种方法可以将PDO集成到所有类中?或者至少是每一类——而不是每一种血腥的方法?

以下是一个非常简单的例子,说明了curretnly的工作原理,但正如我所说的乏味:

<?php
 $db = new PDO("mysql:host=localhost;dbname=blaa;", "blaa", "blaa");
class test{
function show($col, $id){
    global $db;
    $result = $db->prepare("SELECT ".$col." FROM products WHERE id = :id");
    $result->execute(array("id"=>$id));
    $row = $result->fetch();
    echo $row[$col];
}
}
$show = new test();
$show->show("price", 1);
?>

所以我可以在方法"show()"中使用我的PDO,但如果我要添加另一个方法,我必须再次在其中放入"global$db;"。。。

那么,我如何不只是在一个方法中全球化它,而是在所有类别中全球化它呢?我尝试将PDO类继承到"test"类中,但没有成功;我试着使用一个构造函数,比如:

<?php
$db = new PDO("mysql:host=localhost;dbname=blaa;", "blaa", "blaa");
class test{
    public $db;
function __construct($db){
           $this->db = $db;
    }
function show($col, $id){
    $result = $db->prepare("SELECT ".$col." FROM products WHERE id = :id");
    $result->execute(array("id"=>$id));
    $row = $result->fetch();
    echo $row[$col];
}
}
$show = new test($db);
$show->show("price", 1);
?>

但那没用。。

任何帮助都将不胜感激!

谢谢-Wylie

$this->db = $db;

意味着您将$db分配给了$this->db,而不是相反!

因此,您必须在类中使用$this->db,而不是$db

$result = $this->db->prepare("SELECT ".$col." FROM products WHERE id = :id");

"你的常识"是对的。但我想补充一点,您可以也应该使用singleton模式:创建一个类,其目的是维护与数据库的唯一连接。

class Database {
    private static $instance = null;
    private $pdo;
    private function __construct() {
        $this->pdo = new PDO("mysql:host=localhost;dbname=blaa;", "blaa", "blaa");
    }
    public static function get() {
        if(is_null(self::$instance))
            self::$instance = new Database();
        return self::$instance;
    }
}

然后,每次需要访问数据库时,不将PDO对象存储为实例属性,而是使用:

$db = Database::get();

你的例子会变成:

class test {
    function __construct() {
        // You don't need this anymore, unless you have other things to do in the constructor
    }
    function show($col, $id) {
        $db = Database::get();
        $result = $db->prepare("SELECT ".$col." FROM products WHERE id = :id");
        $result->execute(array("id"=>$id));
        $row = $result->fetch();
        echo $row[$col];
    }
}

如果不想在每个需要的方法中调用Database::get,可以在构造函数中调用一次。

class test {
    private $db;
    function __construct() {
        $this->db = Database::get();
    }
    function show($col, $id) {
        $result = $this->db->prepare("SELECT ".$col." FROM products WHERE id = :id");
        $result->execute(array("id"=>$id));
        $row = $result->fetch();
        echo $row[$col];
    }
}