just do it

php连接数据库类之单件模式

php连接数据库类之单件模式
单件模式是一种用于确保整个应用程序中只有一个类实例且这个实例所占资源在整个应用程序中是共享时的程序设计方法(根据实际情况,可能需要几个类实例)。在某些情况下,这种程序设计方法是很有用处的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
class DB{
	private $host;    //服务器地址
	private $user;    //数据库用户
	private $pass;   //数据库密码
	private $dbname;  //数据库名
	private $chars;   //字符编码
	private $port;    //端口号
 
	private $link;
    private static $object;
	private  function __construct($arrs){
		$this->host = isset($arrs['host'])?$arrs['host']:'localhost';
		$this->user = isset($arrs['user'])?$arrs['user']:'root';
		$this->pass = isset($arrs['pass'])?$arrs['pass']:'';
		$this->dbname = $arrs['dbname'];
		$this->chars = isset($arrs['chars'])?$arrs['chars']:'utf8';
		$this->port = isset($arrs['port'])?$arrs['port']:3306;
 
		$this->connect();   //连接数据库
	    $this->select_db(); //选择数据库
	    $this->set_names();  //设置编码
	}
	private function __clone(){
 
	}
 
   public static function mysql($arrs){
   	if(!is_object(self::$object)){
   		self::$object = new self($arrs); 
   	}
   	    return self::$object;
 
   }
	private function connect(){
		$this->link = mysql_connect($this->host,$this->user,$this->pass);
		if(!$this->link){
			echo 'connect failed';
		}
	}
 
	private function query($sql){
		$result = mysql_query($sql,$this->link);
		if(!$result){
			echo mysql_errno($this->link).'-'.mysql_error($this->link);
		}
		return $result;
	}
 
	private function select_db(){
		$this->query("use {$this->dbname}");
	}
 
	private function set_names(){
		$this->query("set names {$this->chars}");
	}
 
	public function get_all($sql){
		$result = $this -> query($sql);
		while($res = mysql_fetch_assoc($result)){
			$r_all[] = $res;
		}
		return $r_all;
		mysql_free_result($result);
 
	}
 
	public function get_row($sql){
		if(strpos($sql,'limit') == FALSE){
			$sql .= ' limit 1';
		}
		$result = $this->query($sql);
		return mysql_fetch_assoc($result);
        mysql_free_result($result);
	}
 
	function __destruct(){
		is_resource($this->link)?mysql_close($this->link):'';
	}
 
}
 
$my = DB::mysql(array(
'pass'=>'root',
'dbname'=>'ecshop'
));
$sql = 'select goods_name,shop_price from goods';
$all = $my->get_all($sql);
var_dump($all);
$row = $my->get_row($sql);
var_dump($row);
点赞