Home  >  Article  >  Backend Development  >  Introduction and examples of PHP singleton pattern

Introduction and examples of PHP singleton pattern

WBOY
WBOYOriginal
2016-07-25 09:07:28970browse
  1. private static $_instance;
Copy code

2), constructors and clone functions must be declared private to prevent external programs from new classes and lose the meaning of the singleton mode:

  1. private function __construct()
  2. {
  3. $this->_db = pg_connect('xxxx');
  4. }
  5. private function __clone()
  6. {
  7. }//Override __clone() method, prohibited Clone
Copy code

(3). You must provide a public static method to access this instance (usually the getInstance method), thereby returning a reference to the unique instance

  1. public static function getInstance()
  2. {
  3. if(! (self::$_instance instanceof self) )
  4. {
  5. self::$_instance = new self();
  6. }
  7. return self::$ _instance;
  8. }
Copy code

2. Why should we use the singleton mode of PHP design pattern? 1. PHP Disadvantages: The PHP language is an interpreted scripting language. This operating mechanism ensures that after each PHP page is interpreted and executed, all related resources will be recycled. In other words, PHP has no way to make an object resident in memory at the language level. This is different from compiled types such as asp.net and Java. For example, in Java, a singleton will always exist throughout the life cycle of the application. Variables are cross-page level and can truly make this instance unique in the application life cycle. However, in PHP, all variables, whether they are global variables or static members of the class, are page-level. Every time the page is executed, a new object will be re-established and will be cleared after the page is executed. It seems that PHP The singleton mode is meaningless, so I think the PHP singleton mode is very meaningful only when multiple application scenarios occur in a single page-level request and need to share the same object resource.

2. Application occasions of singleton mode in PHP: 1) Interaction between application and database There will be a large number of database operations in an application, such as the act of connecting to the database through a database handle. Using the singleton mode can avoid a large number of new operations, because each new operation consumes memory resources and system resources. 2), control configuration information If a class is needed in the system to globally control certain configuration information, then it can be easily implemented using the singleton pattern.

3. How to implement singleton mode? 1. Common database access examples:

  1. ......
  2. //Initialize a database handle
  3. $db = new DB(...);
  4. //Add user information
  5. $db->addUserInfo (...);
  6. ......
  7. //Access the database in the function to find user information
  8. function getUserInfo()
  9. {
  10. $db = new DB(...);//new again Database class, establish a connection with the database
  11. $db = query(....);//Access the database according to the query statement
  12. }
  13. ?>
Copy the code

2. Apply singleton mode to operate the database :

  1. class DB
  2. {
  3. private $_db;
  4. private static $_instance;
  5. private function __construct(...)
  6. {
  7. $this->_db = pg_connect(.. .);//postgrsql
  8. }
  9. private function __clone() {}; //Override the __clone() method and prohibit cloning
  10. public static function getInstance()
  11. {
  12. if(! (self::$_instance instanceof self) ) {
  13. self::$_instance = new self();
  14. }
  15. return self::$_instance;
  16. }
  17. public function addUserInfo(...)
  18. {
  19. }
  20. public function getUserInfo(... )
  21. {
  22. }
  23. }
  24. //test
  25. $db = DB::getInstance();
  26. $db->addUserInfo(...);
  27. $db->getUserInfo(...);
  28. ?>
Copy code

3. In-depth understanding

  1. /**
  2. Database operation class
  3. @link http://bbs.it-home.org
  4. */
  5. class db {
  6. public $conn;
  7. public static $sql;
  8. public static $instance=null;
  9. private function __construct(){
  10. require_once('db.config.php');
  11. $this->conn = mysql_connect($db['host'],$db['user'],$db['password']);
  12. if(!mysql_select_db($db['database'],$this->conn)){
  13. echo "失败";
  14. };
  15. mysql_query('set names utf8',$this->conn);
  16. }
  17. public static function getInstance(){
  18. if(is_null(self::$instance)){
  19. self::$instance = new db;
  20. }
  21. return self::$instance;
  22. }
  23. /**
  24. * Query database
  25. */
  26. public function select($table,$condition=array(),$field = array()){
  27. $where='';
  28. if(!emptyempty($condition)){
  29. foreach($condition as $k=>$v){
  30. $where.=$k."='".$v."' and ";
  31. }
  32. $where='where '.$where .'1=1';
  33. }
  34. $fieldstr = '';
  35. if(!emptyempty($field)){
  36. foreach($field as $k=>$v){
  37. $fieldstr.= $v.',';
  38. }
  39. $fieldstr = rtrim($fieldstr,',');
  40. }else{
  41. $fieldstr = '*';
  42. }
  43. self::$sql = "select {$fieldstr} from {$table} {$where}";
  44. $result=mysql_query(self::$sql,$this->conn);
  45. $resuleRow = array();
  46. $i = 0;
  47. while($row=mysql_fetch_assoc($result)){
  48. foreach($row as $k=>$v){
  49. $resuleRow[$i][$k] = $v;
  50. }
  51. $i++;
  52. }
  53. return $resuleRow;
  54. }
  55. /**
  56. * Add a record
  57. */
  58. public function insert($table,$data){
  59. $values = '';
  60. $datas = '';
  61. foreach($data as $k=>$v){
  62. $values.=$k.',';
  63. $datas.="'$v'".',';
  64. }
  65. $values = rtrim($values,',');
  66. $datas = rtrim($datas,',');
  67. self::$sql = "INSERT INTO {$table} ({$values}) VALUES ({$datas})";
  68. if(mysql_query(self::$sql)){
  69. return mysql_insert_id();
  70. }else{
  71. return false;
  72. };
  73. }
  74. /**
  75. * Modify a record
  76. */
  77. public function update($table,$data,$condition=array()){
  78. $where='';
  79. if(!emptyempty($condition)){
  80. foreach($condition as $k=>$v){
  81. $where.=$k."='".$v."' and ";
  82. }
  83. $where='where '.$where .'1=1';
  84. }
  85. $updatastr = '';
  86. if(!emptyempty($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. * Delete record
  97. */
  98. public function delete($table,$condition){
  99. $where='';
  100. if(!emptyempty($condition)){
  101. foreach($condition as $k=>$v){
  102. $where.=$k."='".$v."' and ";
  103. }
  104. $where='where '.$where .'1=1';
  105. }
  106. self::$sql = "delete from {$table} {$where}";
  107. return mysql_query(self::$sql);
  108. }
  109. public static function getLastSql(){
  110. echo self::$sql;
  111. }
  112. }
  113. $db = db::getInstance();
  114. //$list = $db->select('demo',array('name'=>'tom','password'=>'ds'),array('name','password'));
  115. //echo $db->insert('demo',array('name'=>'最近你啦','password'=>'123'));
  116. //echo $db->update('demo',array("name"=>'xxx',"password"=>'123'),array('id'=>1));
  117. echo $db->delete('demo',array('id'=>'2'));
  118. db::getLastSql();
  119. echo "
    ";  
  120. ?>
复制代码



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn