Implementation of Common Operating Class in PHP-Database Operating Class

Thank you for your collection and praise, which is my greatest encouragement.

Source Code

<?php
/**
 * TODO:Database Model Class
 * Author: entner
 * time:   2017-5-6
 * version:1.0
 */

Class DB{
    protected $HOST = '127.0.0.1';     //Host address
    protected $DATABASE;               
    protected $USER ="root";           //Database username
    protected $ROOT ="root";           //Database User Password
    private static $resource;          //Database Connection Resource Handle 
    private static  $instance;        //A unique instance of a class saved by static variables

    /**
     * Constructors and clones must be declared private to prevent external acquisition
     */
    private function __construct(){    
            echo "hello";
    }

    /**
     * TODO:Get an instance of an operation class
     * Singleton mode: Give only one entry
     * static :  Static connections without duplicate declarations
     */
    public static function getInstance(){
        if(!self::$instance instanceof self){
            self::$instance = new self();
        }
        return self::$instance;
    }


    /**
    * TODO:Database Connection
    * @pagram $dbname string Database name
    */
    public function connect($dbname = "mail"){
        $this->DATABASE = $dbname;
        /*    Determine whether the database is connected or not     */
        if(!self::$resource){
            self::$resource = mysqli_connect($this->HOST,$this->USER,$this->ROOT,$this->DATABASE);
            /*    If the database connection fails        */
            if(!self::$resource){
                throw new Execption('mysql connect error'.mysqli_connect_error());
            }
            /*   Setting Code   */
            mysqli_query(self::$resource,"set names UTF8");
        }
        return self::$resource;
    }



}

/**********Coding 1*********************
$res = DB::getInstance()->connect("base");    
print_r($res);
die;
********************************/


/**********Coding 2*********************
 $res = new DB();
 $res::getInstance()->connect();  
 Because the constructor is private, this sentence produces a fatal error
********************************/


/**********Coding 3*********************
$a = DB::getInstance();
$a->connect();
                        
$b = DB::getInstance();
$b->connect();

echo "<pre>";
print_r($a);
print_r($b);

Only one constructor is executed to indicate that $a $b is the same instance of the class
********************************/

analysis

If you don't look at the constructor and getInstance method, you can see that it's very simple to implement the database operation class. Just take the parameters of the database connection function as the class member variables and call them. But here we use a simple design pattern - the singleton pattern. In a word, with it, the code will be more convenient and robust. Let's talk about it briefly below.

Why use singleton mode?

In fact, from the technical point of view, the main consideration is to save memory resources and improve the performance of the system, but what we can actually feel is that it is more convenient, and more powerful, so we use it.

What is the singleton pattern?

For example, the building has only one entrance, which is convenient for control. In object-oriented terms, it is a class with only one instance, which is convenient for management.

How does the code part implement the singleton pattern?

  1. First, declare a private constructor so that you can't instantiate multiple objects with new outside. You can try coding 2 code and it will report an error.

  2. Construct a public entry to get instances of classes. There are always instances available for scattering. Note that this self refers to the current class, and instanceof checks whether the current variable is an instance of the class.

How to check the effect of singletons?

You can use coding 3 code to view the output, and then you will find that the constructor only executes once, indicating that after the first instantiation of the object, the subsequent variables refer to the object consistently, indicating that there is actually only one instance.

Why must the getInstance method be static?

Because there are two ways to instantiate objects, one is New Class, the other is Class::method, because the first one can not be used (the private rule can not refer to class members outside), so we can only take the second method.
Moreover, functions are variables, static variables, no matter how many times they are referenced, will not be generated repeatedly, which saves space. The problem of multi-threading is not considered here.

Reference link

Analysis and Practice of PHP Singleton Model
PHP design pattern singleton pattern
Five Ways to Realize Singleton Mode
How much do you know about static and non-static methods in language?

epilogue

If you don't understand or feel wrong, please leave a message.

Keywords: PHP Database MySQL

Added by cringe on Fri, 14 Jun 2019 22:16:55 +0300