1

我有一个使用 PDO 的数据库类。这是它的一部分示例:

class db {
private $host;
private $username;
private $password;
private $con;
    private $pdo;

public function __construct( $database = "dnname" )
{
    $this->host = "localhost";
    $this->username = "username";
    $this->password = "pass";
            $conStr = "host={$this->host};dbname={$database}";
            try {
                $this->pdo = new PDO( "mysql:$conStr", $this->username, $this->password );
                $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            }
            catch( PDOException $e ) {
                echo "error ". $e->getMessage();
            }
}

public function fetch_single_row($sql, $data)
{
    if( $data !== null )
        $data = array_values( $data ); // Incase it's an associative array
    $sel = $this->pdo->prepare( $sql );
    $sel->execute( $data );
    $sel->setFetchMode( PDO::FETCH_OBJ );
    $obj = $sel->fetch();
    return $obj;
}

我想在其他类中使用这个类及其功能(它比我包含的更多)。

我尝试了许多不同的方法,但到目前为止唯一有效的是在每个新类中启动一个新的 db 实例,我认为这是不好的做法。例如:

class cms {
   function cms(){
       $this->db = new db();
   }

   function is_admin($id) {
    if($this->db->fetch_single_row("SELECT id FROM user WHERE id = ? LIMIT 1", array($id))){
        return true;
    } else {
        return false;
    }
}

在我的 index.php 中,我包含这些类并使用它们:

include("db.class.php");
include("cms.class.php");

$cms = new cms();

if($cms->is_admin($id)){
   //code here
}

实现此目的的正确方法是什么?

4

1 回答 1

4

看看 Singleton 设计模式,它非常适合 DB 类

我曾经使用过这样的课程很长一段时间

   abstract class DB
   {

    protected static $instance;

    protected $db;

    protected static $host = 'host';
    protected static $user = 'user';
    protected static $pass = 'pass';
    protected static $database;

    public static function getInstance()
    {
        if (!isset(self::$instance)) self::$instance = new static();

        return self::$instance;
    }

    protected function __construct()
    {
        $this->db = new PDO(sprintf('mysql:host=%s;dbname=%s', static::$host, static::$database), static::$user, static::$pass);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public static function db()
    {
        return static::getInstance()->db;
    }

    public function fetch_single_row($sql, $data)
    {
        if( $data !== null )
            $data = array_values( $data ); // Incase it's an associative array
        $sel = self::db()->prepare( $sql );
        $sel->execute( $data );
        $sel->setFetchMode( PDO::FETCH_OBJ );
        $obj = $sel->fetch();
        return $obj;
    }
}

然后,我将为需要连接的每个不同数据库扩展该类

class Main extends DB
{
    protected static $database = 'db';
}

然后你可以像这样使用这个类

$db = Main::getInstance();
$obj = $db->fetch_single_row($sql, $data);
于 2012-07-22T05:10:33.847 回答