PDO操作データベースのカプセル化
1、MysqlPdo.class.php ファイルを作成して、PDO 操作データベースをカプセル化します。
具體的なコードは次のとおりです。
<?php class MysqlPdo{ private $dbConfig=array( 'db'=>'mysql', 'host'=>'localhost', 'port'=>'3306', 'user'=>'root', 'pwd'=>'', 'charset'=>'utf8', 'dbname'=>'' ); private static $instance; //單例模式 private $db; //PDO實(shí)例 private $data=array(); //操作數(shù)據(jù) private function __construct($params) { $this->dbConfig=array_merge($this->dbConfig,$params); $this->connect(); } //連接服務(wù)器 private function connect(){ //mysql:host=localhost //mysql:host:localhost;port=3306;dbname=php;charset=utf-8 $dsn="{$this->dbConfig['db']}:host={$this->dbConfig['host']};port={$this->dbConfig['port']};dbname={$this->dbConfig['dbname']};charset={$this->dbConfig['charset']}}"; try{ //實(shí)例化PDO $this->db=new PDO($dsn,$this->dbConfig['user'],$this->dbConfig['pwd']); }catch (PDOException $exception){ die("數(shù)據(jù)庫(kù)連接失敗"); } } public static function getInstance($params=array()){ if(!self::$instance instanceof self){ self::$instance=new self($params); } return self::$instance; //返回對(duì)象 } //私有化克隆,防止外部調(diào)用clone $對(duì)象 生成新的對(duì)象,因?yàn)槭菃卫J? private function __clone() { // TODO: Implement __clone() method. } //通過(guò)預(yù)處理方式執(zhí)行sql public function query($sql,$batch=false){ $data=$batch?$this->data:array($this->data); $this->data=array(); //通過(guò)預(yù)處理方式執(zhí)行SQL $stmt=$this->db->prepare($sql); foreach($data as $v){ if($stmt->execute($v)===false){ die("數(shù)據(jù)庫(kù)PDO預(yù)處理操作失敗"); } } return $stmt; } public function data($data){ $this->data=$data; return $this; //返回對(duì)象自身用于連貫操作 } //取得一行結(jié)果 public function fetchRow($sql){ return $this->query($sql)->fetch(PDO::FETCH_ASSOC);//返回索引數(shù)組 } //取得多行結(jié)果 public function fetchAll($sql){ return $this->query($sql)->fetchAll(PDO::FETCH_ASSOC); } }
1. このカプセル化クラスはシングルトン モードを採(cǎi)用し、構(gòu)築メソッドとクローン作成メソッドをプライベート化して、インスタンス化されるオブジェクトが 1 つだけになるようにし、データベース接続リソースを節(jié)約します。 # #2、データベース接続オブジェクトが作成されるたびに getInstance() を呼び出す必要があります。
getInstance にデータベース構(gòu)成情報(bào)を渡して、受信したデータベース構(gòu)成情報(bào)を使用するオブジェクトをインスタンス化するときにコンストラクターを自動(dòng)的に呼び出します。元の情報(bào)とマージして、他のデータベースへの接続拡張を容易にします。データベースを変更するには、構(gòu)成情報(bào)を変更するだけで済みます。3. 前処理を通じて SQL ステートメントを?qū)g行します
##4、一貫した操作の使用
5、クエリ結(jié)果セットの処理
# #上記はデータベース クラスのカプセル化です