doubinduo3364 2012-07-22 04:21
浏览 117
已采纳

在其他PHP类中使用PDO数据库类

I have a database class that uses PDO. Here's a portion example of it:

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;
}

I would like to use this class and its functions (it has more than I've included) inside other classes.

I have tried many many different things, but the only thing that works so far is starting a new instance of db in every new class which I think is bad practice. For instance:

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;
    }
}

in my index.php, I include these classes and use them:

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

$cms = new cms();

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

What is the correct way to accomplish this?

  • 写回答

1条回答 默认 最新

  • dongsou3041 2012-07-22 05:10
    关注

    Take a look into the Singleton Design Pattern, it works great for a DB class

    I used to use a class like this for quite a while

       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;
        }
    }
    

    I would then extend that class for each different database I would need to connect to

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

    You can then use the class like this

    $db = Main::getInstance();
    $obj = $db->fetch_single_row($sql, $data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题