研究php单例模式实现数据库类

  实现单例模式:单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。

  单例模式的逻辑:类里面声明一个静态的方法和变量,静态变量用来存储唯一的实例,静态方法作为类向外的唯一的接口,并在里面做判断,当静态变量有实例时候直接返回,没有则new一个实例赋值在静态变量里面。构造函数里面放链接数据库的操作,因为静态方法中实现了控制了只实例化一次,所以达到只链接数据库一次。在类外部访问静态方法;

  简单类如下:

 1     class Con_db{
 2         private static $dbObj = null;
 3         private $con;
 4         private $result;
 5         private $row;
 6         private $newsItem;
 7         /**
 8          * 构造函数
 9          * @param [type] $host     [数据库地址]
10          * @param [type] $username [数据库名称]
11          * @param [type] $psw      [数据库密码]
12          * @param [type] $database [数据库]
13          */
14         private function __construct($host,$username,$psw,$database){
15             $this->con = mysql_connect($host,$username,$psw);
16             if(!$this->con){
17                 die("链接失败");
18             }
19             mysql_set_charset("utf-8");
20             mysql_select_db($database);
21         }
22         /**
23          * 获取一次性对象
24          * @return 实例对象
25          */
26         public static function getInstance($host,$username,$psw,$database){
27             if(is_null(self::$dbObj)){
28                 self::$dbObj = new self($host,$username,$psw,$database);
29             }
30             return self::$dbObj;
31         }
32 
33         /**
34          *     数据库查询语句
35          */
36         private function query($sql){
37             if($sql){
38                 $this->result = mysql_query($sql);
39                 if($this->result && mysql_num_rows($this->result)){
40                     return $this->result;
41                 }else{
42                     return false;
43                 }
44             }else{
45                 die("必须填写查询语句!");
46             }    
47         }
48         /**
49          * 查询多条语句
50          * @param $sql 查询语句
51          * return string;
52          */
53         private function getAll($sql){
54               $this->result = mysql_query($sql);
55           if($this->result && mysql_num_rows($this->result)){
56               $this->newsItem = array();
57             while($this->row = mysql_fetch_assoc($this->result)){
58               $this->newsItem[] = $this->row;
59             }
60           }
61           return $this->newsItem;
62         }
63         /**
64          * 查询一条语句
65          * @param $sql 查询语句
66          * return string;
67          */
68         private function getone($sql){
69               $this->result = mysql_query($sql);
70               if($this->result && mysql_num_rows($this->result)){
71                return $this->row = mysql_fetch_assoc($this->result);
72             }
73         }
74     }
75     $db = Con_db::getInstance("localhost","root","root","szwengdo_com");
76     $sql = "select * from wd_cases";
77     $row = $db->getone($sql);
78     var_dump($row);    

    第一次研究,希望改正!!

原文地址:https://www.cnblogs.com/panhe-xue/p/6225461.html