Using PDO database class within other PHP classes

后端 未结 1 1487
感情败类
感情败类 2021-01-07 10:37

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


        
相关标签:
1条回答
  • 2021-01-07 11:17

    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);
    
    0 讨论(0)
提交回复
热议问题