簡體   English   中英

嘗試使用PDO和單例模式創建數據庫連接

[英]Trying to create a database connection with PDO and singleton pattern

我一直在嘗試使用PDO和singleton創建數據庫連接。 我想我已經完成了但是我不確定我是否使用了正確的單例模式。

我也不確定我是否正確使用了__clone()__wakeup()方法。 我沒有測試它們的知識。

任何人都可以告訴我,如果我的方法是在正確的道路上,如果我正確使用單身模式? 我很擅長設計模式。

這是我的代碼:

<?php

require_once 'config.php';

class dbConn{

// Variable to store connection object.
protected static $db;

// Assign variables from config.php.
private $host   = DB_HOST;
private $dbuser = DB_USER;
private $dbpass = DB_PASS;
private $dbname = DB_NAME;

// Private construct - class cannot be instatiated externally.
private function __construct() {

    try {
        // Try to create PDO object to the $db variable.
        $pre = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        self::$db = new PDO($pre, $this->dbuser, $this->dbpass);
        self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    // If not able to connect to database.
    catch (PDOException $e) {
        echo "Could not connect: " . $e->getMessage();
    } 
}

// Get connection function.
public static function getConnection() {

// Only if no connection object exists it creates one, because we only want one instance.
    if (!self::$db) {
// New connection object.
        new dbConn();
}
    return self::$db;
}

public function __clone() {
        return false;
    }

public function __wakeup(){
        return false;
    }
}

$db = dbConn::getConnection()

?>

這不是單例模式:php中的單例是一個類,它將自身的唯一實例存儲在靜態變量中。

恕我直言是不使用單身類的好習慣,靜態分類可以做同樣的事情。

對於你想要獲得的東西,你可以看到依賴注意或

創建這樣的東西:

class Database extends PDO {
   private $engine = 'mysql';
   private $host = 'localhost';
   private $database = 'Crumbs';
   private $user = 'root';
   private $pass = 'adminuser';

   public function __construct()
   {
      $dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
      parent::__construct( $dns, $this->user, $this->pass );
   } 
}

然后使用:

$db = new Database();

只是為了你的知識:

依賴注入是一種模式,如:

class Class {
   private $dependency;
   public function __construct($dep) {
      $this->$dependency = $dep;
   }

   function use_dependency( ... ) {
      $dep = $this->$dependency;
      ...
      $dep->action();
      ...
    }
}

$dep = new Dependency();
$c = new Class( $dep );

單身模式如下:

class Singleton
{
    protected static $instance = null;
    protected function __construct()
    {
        //Thou shalt not construct that which is unconstructable!
    }
    protected function __clone()
    {
        //Me not like clones! Me smash clones!
    }

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

但我重申這是不好的做法。

另請注意,在反序列化后調用__wakeup(請參閱http://www.php.net/manual/en/language.oop5.magic.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM