当前位置: 代码迷 >> PHP >> PHP 单例模式解析跟实战
  详细解决方案

PHP 单例模式解析跟实战

热度:113   发布时间:2016-04-28 18:19:44.0
PHP 单例模式解析和实战

一、什么是单例模式?

1、含义???

?? 作为对象的创建模式,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统全局地提供这个实例。它不会创建实例副本,而是会向单例类内部存储的实例返回一个引用。

2、单例模式的三个要点:

(1). 需要一个保存类的唯一实例的静态成员变量:

[php]?view plaincopyprint?
?
  1. private?static?$_instance;???

?

(2).?构造函数和克隆函数必须声明为私有的,防止外部程序new类从而失去单例模式的意义:

?

[php]?view plaincopyprint?
?
  1. private?function?__construct()???
  2. {???
  3. ????$this->_db?=?pg_connect('xxxx');??
  4. }???
  5. private?function?__clone()??
  6. {??
  7. }//覆盖__clone()方法,禁止克隆??
  8. ???

?

(3). 必须提供一个访问这个实例的公共的静态方法(通常为getInstance方法),从而返回唯一实例的一个引用?

[php]?view plaincopyprint?
?
  1. public?static?function?getInstance()????
  2. {????
  3. ????if(!?(self::$_instance?instanceof?self)?)???
  4. ????{????
  5. ????????self::$_instance?=?new?self();????
  6. ????}??
  7. ????return?self::$_instance;????
  8. ??
  9. }???




二、为什么要使用单例模式?

1、PHP缺点:????????

??????? PHP语言是一种解释型的脚本语言,这种运行机制使得每个PHP页面被解释执行后,所有的相关资源都会被回收。也就是说,PHP在语言级别上没有办法让某个对象常驻内存,这和asp.net、Java等编译型是不同的,比如在Java中单例会一直存在于整个应用程序的生命周期里,变量是跨页面级的,真正可以做到这个实例在应用程序生命周期中的唯一性。然而在PHP中,所有的变量无论是全局变量还是类的静态成员,都是页面级的,每次页面被执行时,都会重新建立新的对象,都会在页面执行完毕后被清空,这样似乎PHP单例模式就没有什么意义了,所以PHP单例模式我觉得只是针对单次页面级请求时出现多个应用场景并需要共享同一对象资源时是非常有意义的。

?

2、单例模式在PHP中的应用场合:

(1)、应用程序与数据库交互

? ? ? ? 一个应用中会存在大量的数据库操作,比如过数据库句柄来连接数据库这一行为,使用单例模式可以避免大量的new操作,因为每一次new操作都会消耗内存资源和系统资源。

(2)、控制配置信息

? ? ? ? 如果系统中需要有一个类来全局控制某些配置信息, 那么使用单例模式可以很方便的实现.

?

三、如何实现单例模式?

1、普通的数据库访问例子:

[php]?view plaincopyprint?
?
  1. <?php??
  2. ......??
  3. //初始化一个数据库句柄??
  4. $db?=?new?DB(...);??
  5. ??
  6. //添加用户信息??
  7. $db->addUserInfo(...);??
  8. ??
  9. ......??
  10. ??
  11. //在函数中访问数据库,查找用户信息??
  12. function?getUserInfo()??
  13. {??
  14. ????$db?=?new?DB(...);//再次new?数据库类,和数据库建立连接??
  15. ????$db?=?query(....);//根据查询语句访问数据库??
  16. }??
  17. ??
  18. ?>??

?

2、应用单例模式对数据库进行操作:

[php]?view plaincopyprint?
?
  1. <?php??
  2. ??
  3. class?DB????
  4. {????
  5. ????private?$_db;????
  6. ????private?static?$_instance;????
  7. ????
  8. ????private?function?__construct(...)????
  9. ????{????
  10. ????????$this->_db?=?pg_connect(...);//postgrsql????
  11. ????}????
  12. ????
  13. ????private?function?__clone()?{};??//覆盖__clone()方法,禁止克隆????
  14. ????
  15. ????public?static?function?getInstance()????
  16. ????{????
  17. ????????if(!?(self::$_instance?instanceof?self)?)?{????
  18. ????????????self::$_instance?=?new?self();????
  19. ????????}????
  20. ????????return?self::$_instance;????
  21. ????}????
  22. ????
  23. ??????
  24. ??
  25. ????public?function?addUserInfo(...)??
  26. ????{??
  27. ??
  28. ?????
  29. ??
  30. ????}??
  31. ??
  32. ?????public?function?getUserInfo(...)??
  33. ????{???
  34. ??
  35. ????}??
  36. ??
  37. }??
  38. ??
  39. //test??
  40. ??
  41. $db?=?DB::getInstance();??
  42. ??
  43. $db->addUserInfo(...);??
  44. ??
  45. $db->getUserInfo(...);??
  46. ??
  47. ??
  48. ?>??



?


3、深入理解

?

[php]?view plaincopyprint?
?
  1. <?php??
  2. class?db?{??
  3. ????public?$conn;??
  4. ????public?static?$sql;??
  5. ????public?static?$instance=null;??
  6. ????private?function?__construct(){??
  7. ????????require_once('db.config.php');??
  8. ????????$this->conn?=?mysql_connect($db['host'],$db['user'],$db['password']);??
  9. ????????if(!mysql_select_db($db['database'],$this->conn)){??
  10. ????????????echo?"失败";??
  11. ????????};??
  12. ????????mysql_query('set?names?utf8',$this->conn);?????????
  13. ????}??
  14. ????public?static?function?getInstance(){??
  15. ????????if(is_null(self::$instance)){??
  16. ????????????self::$instance?=?new?db;??
  17. ????????}??
  18. ????????return?self::$instance;??
  19. ????}??
  20. ????/**?
  21. ?????*?查询数据库?
  22. ?????*/??
  23. ????public?function?select($table,$condition=array(),$field?=?array()){??
  24. ????????$where='';??
  25. ????????if(!empty($condition)){??
  26. ??????????????
  27. ????????????foreach($condition?as?$k=>$v){??
  28. ????????????????$where.=$k."='".$v."'?and?";??
  29. ????????????}??
  30. ????????????$where='where?'.$where?.'1=1';??
  31. ????????}??
  32. ????????$fieldstr?=?'';??
  33. ????????if(!empty($field)){??
  34. ??????????????
  35. ????????????foreach($field?as?$k=>$v){??
  36. ????????????????$fieldstr.=?$v.',';??
  37. ????????????}??
  38. ?????????????$fieldstr?=?rtrim($fieldstr,',');??
  39. ????????}else{??
  40. ????????????$fieldstr?=?'*';??
  41. ????????}??
  42. ????????self::$sql?=?"select?{$fieldstr}?from?{$table}?{$where}";??
  43. ????????$result=mysql_query(self::$sql,$this->conn);??
  44. ????????$resuleRow?=?array();??
  45. ????????$i?=?0;??
  46. ????????while($row=mysql_fetch_assoc($result)){??
  47. ????????????foreach($row?as?$k=>$v){??
  48. ????????????????$resuleRow[$i][$k]?=?$v;??
  49. ????????????}??
  50. ????????????$i++;??
  51. ????????}??
  52. ????????return?$resuleRow;??
  53. ????}??
  54. ????/**?
  55. ?????*?添加一条记录?
  56. ?????*/??
  57. ?????public?function?insert($table,$data){??
  58. ????????$values?=?'';??
  59. ????????$datas?=?'';??
  60. ????????foreach($data?as?$k=>$v){??
  61. ????????????$values.=$k.',';??
  62. ????????????$datas.="'$v'".',';??
  63. ????????}??
  64. ????????$values?=?rtrim($values,',');??
  65. ????????$datas???=?rtrim($datas,',');??
  66. ????????self::$sql?=?"INSERT?INTO??{$table}?({$values})?VALUES?({$datas})";??
  67. ????????if(mysql_query(self::$sql)){??
  68. ????????????return?mysql_insert_id();??
  69. ????????}else{??
  70. ????????????return?false;??
  71. ????????};??
  72. ?????}??
  73. ?????/**?
  74. ??????*?修改一条记录?
  75. ??????*/??
  76. ????public?function?update($table,$data,$condition=array()){??
  77. ????????$where='';??
  78. ????????if(!empty($condition)){??
  79. ??????????????
  80. ????????????foreach($condition?as?$k=>$v){??
  81. ????????????????$where.=$k."='".$v."'?and?";??
  82. ????????????}??
  83. ????????????$where='where?'.$where?.'1=1';??
  84. ????????}??
  85. ????????$updatastr?=?'';??
  86. ????????if(!empty($data)){??
  87. ????????????foreach($data?as?$k=>$v){??
  88. ????????????????$updatastr.=?$k."='".$v."',";??
  89. ????????????}??
  90. ????????????$updatastr?=?'set?'.rtrim($updatastr,',');??
  91. ????????}??
  92. ????????self::$sql?=?"update?{$table}?{$updatastr}?{$where}";??
  93. ????????return?mysql_query(self::$sql);??
  94. ????}??
  95. ????/**?
  96. ?????*?删除记录?
  97. ?????*/??
  98. ?????public?function?delete($table,$condition){??
  99. ????????$where='';??
  100. ????????if(!empty($condition)){??
  101. ??????????????
  102. ????????????foreach($condition?as?$k=>$v){??
  103. ????????????????$where.=$k."='".$v."'?and?";??
  104. ????????????}??
  105. ????????????$where='where?'.$where?.'1=1';??
  106. ????????}??
  107. ????????self::$sql?=?"delete?from?{$table}?{$where}";??
  108. ????????return?mysql_query(self::$sql);??
  109. ??????????
  110. ?????}??
  111. ??????
  112. ????public?static?function?getLastSql(){??
  113. ????????echo?self::$sql;??
  114. ????}??
  115. ??????
  116. ??????
  117. ??????
  118. }??
  119. ??
  120. $db?=?db::getInstance();??
  121. //$list?=?$db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password'));??
  122. //echo?$db->insert('demo',array('name'=>'最近你啦','password'=>'123'));??
  123. //echo?$db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1));??
  124. echo?$db->delete('demo',array('id'=>'2'));??
  125. db::getLastSql();??
  126. echo?"<pre>";??
  127. ?>??

转载自:?http://blog.csdn.net/jungsagacity/article/details/7618587

?

  相关解决方案