您的位置 >>> 星想互联 >>> 编程技术 >>> PHP基础
学习笔记:单例模式实现封装PDO类
点击数:3592  发布时间2017-09-19 19:41:32

设计模式之单例模式 :

咸宁网站建设公司在建站过程中,通常采用单例模式为对象的创建模式, 单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例

* $_instance必须声明为静态的私有变量

* 构造函数和析构函数必须声明为私有,防止外部程序new

* 类从而失去单例模式的意义

* getInstance()方法必须设置为公有的,必须调用此方法

* 以返回实例的一个引用

* ::操作符只能访问静态变量和静态函数

* new对象都会消耗内存

* 使用场景:最常用的地方是数据库连接。

* 使用单例模式生成一个对象后,

* 该对象可以被其它众多对象所使用。

下面是一个典型的案件:

<?php 
//header("Content-type: text/html; charset=gb2312"); 
class mymvc{
 private $name="旺仔";
 private $age="4岁";

 private static $link;

 private function __construct(){
       echo $this->name;
       echo $this->age;
 }
   

    public static function gets(){
       self::$link=new self();
    }

}

mymvc::gets();

?>

php的应用主要在于数据库, 所以一个应用中会存在大量的数据库操作, 在使用面向对象的方式开发时(废话), 如果使用单例模式, 则可以避免大量的new 操作消耗的资源。

下面是一个经典的方法:

<?php 
header("Content-type: text/html; charset=gb2312"); 
 class mydb{
  private $dbconfig=array(
           'db'=>'mysql',
           'host'=>'localhost',
           'user'=>'root',
           'pwd'=>'',
           'dbname'=>'news',
           'ci'=>'set names gb2312',
   );
     //单例模式,本类对象引用
 private static $instance;

 //PDO实例
 private $db;

 /**
   * 私有构造方法
  * param $params array 数据库连接信息
  */
  private function __construct($params){
   $this->dbconfig=array_merge($this->dbconfig,$params);
   $this->connect();//调用connect方法连接数据库
 }

 private function connect(){
   $dsn="{$this->dbconfig['db']}:host={$this->dbconfig['host']};dbname={$this->dbconfig['dbname']}";
   $this->db=new PDO($dsn,$this->dbconfig['user'],$this->dbconfig['pwd']);
   $this->db->query($this->dbconfig['ci']);
   if(!$this->db){echo "连接失败,检查数据库连接数据";}
  }

 //获得单例模式,返回单例对象
    public static function getinstance($params=array()){
      if(!self::$instance instanceof self){
       self::$instance=new self($params); 
      }
      return self::$instance;
     }

 //克隆私有化,禁止外部克隆
 private function __clone(){}

   /*
  **********执行SQL操作
 **********
  **********
  **********
  **********
    */
  public function query($sql){
   $stmt=$this->db->query($sql);
   return $stmt;
  }

 public function fetchRow($sql){
   return $this->db->query($sql)->fetch(PDO::FETCH_ASSOC);
  }

 public function fetchAll($sql){
   return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  }
   
 }

//数据演示
//$mypdo=new mydb(array());
 $mypdo=mydb::getinstance(array());
 $rs=$mypdo->fetchRow("selects * from news");

var_dump($rs);
 ?>

来源:咸宁网站建设