当前位置:网站首页>Single instance mode of encapsulating PDO with PHP in spare time

Single instance mode of encapsulating PDO with PHP in spare time

2022-07-06 02:43:00 SinMu-L

The following class is to record , Maybe you will use it when writing your own framework later . perform sql The logic of needs itself diy Oh .

The place where the database is connected can also be optimized

The main function :

  1. The singleton pattern ( The sluggard model )
  2. Prevent cloning

The call method is as follows

$res = Db::getInstance();

DB The categories are as follows

Class DB
{
    
 
    // Singleton database class 
    private static $_instance;
    private $pdo;
    private $db_host = "127.0.0.1";
    private $db_user = "root";
    private $db_pwd = "123456";
    private $db_name = "test";
    private $charset = "utf8";
    private $db_port = "3306";
 
 
 
    // Prevent cloning objects 
    private function __clone()
    {
    
    }
 
    // prevent new object  private  modification 
    private function __construct()
    {
    
        $this->connect();
        $this->setCharSet();
    }
 
    /** *  Connect to database  */
    private function connect()
    {
    
        try {
    
            $this->pdo = new PDO("mysql:host=$this->db_host;port=$this->db_port;dbname=$this->db_name", $this->db_user, $this->db_pwd);
            // echo " Successful connection ";
        } catch (Exception $e) {
    
            throw new Exception('MySql Connection error !');
            //  Write log logic ...
            file_put_contents(__DIR__ . '/log/'.strftime('%Y-%m-%d').'.log',$e->getMessage().PHP_EOL,FILE_APPEND);
            return false;
        }
 
    }
 
    // initialization Db Class only needs to execute the static method 
    public static function getInstance(): Db
    {
    
        if (!(self::$_instance instanceof self)){
    
            self::$_instance = new self();
        }
        return self::$_instance;
    }
 
    /** *  Set character set  */
    private function setCharSet(){
    
        $this->pdo->query($this->charset);
    }
 
    //  perform sql sentence ,  No results returned 
    public function exec($sql){
    
        // diy......
    }
 
    //  perform select  sentence , There are returned results 
    public function select(){
    
        // diy....
    }
   }

added php Nostalgic knowledge , Can pay attention to 【php Developer community 】

原网站

版权声明
本文为[SinMu-L]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140001263930.html