Introduction and examples of PHP single-instance mode

Source: Internet
Author: User
Tags php language
    1. private static $_instance;
Copy Code

2), constructors, and clone functions must be declared private to prevent the external program new class from losing the meaning of the singleton pattern:

    1. Private Function __construct ()
    2. {
    3. $this->_db = Pg_connect (' xxxx ');
    4. }
    5. Private Function __clone ()
    6. {
    7. }//overwrite __clone () method, prohibit cloning
Copy Code

(3). You must provide a public static method that accesses this instance (typically the GetInstance method), which returns 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

Second, why use the PHP design mode of the singleton mode? 1, PHP Disadvantage: PHP language is an explanatory type of scripting language, this operating mechanism so that each PHP page is interpreted to execute, all the relevant resources will be recycled. In other words, PHP does not have a language level to allow an object to reside in memory, which is different from the compilation of ASP. NET, Java, such as the single-instance in Java has been in the entire application life cycle, variables are cross-page level, It is true that this instance is unique in the application life cycle. However, in PHP, all variables, whether global variables or static members of the class, are page-level, each time the page is executed, the new object will be re-created, will be emptied after the page executes, so it seems that PHP singleton mode is meaningless, So PHP singleton mode I think it makes sense to just have multiple scenarios for a single page-level request and need to share the same object resource.

2, Singleton mode in PHP applications : 1), Application and database interaction there will be a large number of database operations in an application, such as the database handle to connect the database behavior, using 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 control some configuration information globally, it can be easily implemented using singleton mode.

third, how to achieve a single case 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. Accessing the database in a function to find user information
    8. function GetUserInfo ()
    9. {
    10. $db = new db (...); /again new database class, and database establish connection
    11. $db = Query (...); /database access based on query statement
    12. }
    13. ?>
Copy Code

2, apply the singleton mode to the database operation:

    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 () {}; Overwrite __clone () method, 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 Operations Classes
  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 "Failure";
  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 Records
  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 ' = ' recent you ', ' 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 "
    ";  
Copy Code

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.