PHP-跨类使用PDO连接


PHP - Using PDO connections across classes

[编辑/更新]

请允许我解释一下情况。我有三个文件:

下面是db.class.php。当被调用时,它连接到构造函数中的db,并关闭析构函数中的连接。如果您注意到query()方法,那么它目前只是一个静态INSERT,因为这正是我陷入困境的地方。

<?php
//
// Class: db.class.php
// Desc: Connects to a database and runs PDO queries via MySQL
// Settings:
error_reporting(E_ALL);
////////////////////////////////////////////////////////////
class Db
{
    # Class properties
    private $DBH; // Database Handle
    private $STH; // Statement Handle
    # Func: __construct()
    # Desc: Connects to DB
    public function __construct()
    {
        // Connection information
        $host   = 'localhost';
        $dbname = 'removed';
        $user   = 'removed';
        $pass   = 'removed';
        // Attempt DB connection
        try
        {
            $this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
            $this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo 'Successfully connected to the database!';
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }
    # Func: query(sql statement)
    # Desc: Sends a query to the DB
    public function query($sql_statement)
    {
        $sql = array(':color' => $sql_statement);
        $this->STH = $this->DBH->prepare("INSERT INTO color_table (color) value ( :color )");
        $this->STH->execute($sql);
    }
    # Func: __destruct()
    # Desc: Disconnects from the DB
    public function __destruct()
    {
        // Disconnect from DB
        $this->DBH = null;
        echo 'Successfully disconnected from the database!';
    }
}
?>

下面是colors.class.php。目前,它只有一个插入函数。我要做的基本上是从db.class.php中提取query()函数中的内容,并将其放入此处的insertColor()函数,然后将整个SQL语句(无论是插入、删除还是更新)传递给query()功能。

<?php
//
// Class: colors.class.php
// Desc: Provides methods to create a query to insert,
//       update, or delete a color from the database.
////////////////////////////////////////////////////////////
class Colors
{
    # Class properties
    protected $db;
    # Func: __construct()
    # Desc: Passes the Db object so we can send queries
    public function __construct(Db $db)
    {
        $this->db = $db;
    }
    # Func: insertColor()
    # Desc: Sends an INSERT querystring
    public function insertColor($color)
    {
        $this->db->query($color);
        echo 'Inserted color:' . $color;
    }
}
?>

下面我们有colors.php,上面的一切都是在这里实例化和实现的。所以这里是我传递我真正想要插入数据库的颜色的地方。

<?php
Require('db.class.php');
Require('colors.class.php');
$db = new Db;
$colors = new Colors($db);
$colors->insertColor('TestColor'); // Passing the color here to be put into an insert statement
?>

我主要遇到的问题是,我试图让colors.class.php创建一个PDO语句,然后在它们准备运行时将其传递给db.class.php query()方法。现在,PDO语句只是在query()方法中定义的,但我正在努力避免这种情况。从本质上讲,我想从query()方法中剥离出我所拥有的内容,并将其拆分为Colors类中的三个方法,一个用于插入、更新和删除。

然而,我对OOP编程还很陌生,所有的语法都有问题,我也不知道这是否是一种好的方法。非常感谢任何帮助,如果需要更多细节或信息,请告诉我。

是的,因为$db是方法内部的局部变量。将其作为参数传递:
class Colors
{
  protected $db;
  public function __construct(Db $db = null)
  {
    $this->db = $db;
  }
  public function insertColor()
  {
    if ($this->db != null)
    {
      $this->db->query();
    }
  }
}

query是一种方法,因此必须添加括号:$db->query()

我会从类文件中删除数据库的包含和初始化,并将其放在colors.php中。然后将$db作为参数传递给构造函数:

<?php
Require('db.class.php');
Require('colors.class.php');
$db = new Db;
$colors = new Colors($db);
$colors->insertColor();
?>

我还将删除构造函数中的默认值,因为如果没有数据库,Colors类将无法工作:

public function __construct(Db $db)    // constructor Colors class

最后,我将研究类的自动加载,这样您就不必手动要求它们了。

$db->query;更改为$db->query();

此外,$db需要被声明为全局,才能像那样访问它。可能需要考虑将其作为Colors 的私有财产