Home > Backend Development > PHP Tutorial > PHP singleton mode designs database and connects to Model class

PHP singleton mode designs database and connects to Model class

小云云
Release: 2023-03-22 15:52:02
Original
1686 people have browsed it

Using the idea introduced in "[Java] Singleton Mode" (click to open the link), this database link class can be turned into a singleton. A database query instance will not be created just because multiple users access the website. Drag and drop Slowing down the speed of the entire website puts greater pressure on the website's database, causing the website's speed to drop significantly.

The most critical thing about singleton implementation is the three points:

1. Private constructor. There is no need for a private parameterless constructor like Java. PHP does not Multiple constructors are allowed - even if the constructor parameters are different.

2. Functions of private clone classes

3. Expose a public "create instance function" for calling. This "create instance function" determines if the corresponding instance already exists and returns this instance. Create if there is none.

This ensures that there is only one database connection class.

Let’s use an example to illustrate directly. There is a table user in the database test


First use the singleton mode to design the database connection Model class, and add this The contents of the table are queried on the web page:


    ##
    <?php  
    class db{  
        private $link;  
        //db类单例开始  
        //保存类实例的私有静态成员变量  
        private static $_instance;  
        //定义一个私有的构造函数,确保单例类不能通过new关键字实例化,只能被其自身实例化  
        private function __construct($host,$username,$password,$database){  
            $this->link=mysql_connect($host,$username,$password);  
            if(!$this->link){  
                die("连接失败!");  
            }  
            mysql_query("set names utf8;");  
            mysql_select_db($database);  
        }  
        //定义私有的__clone()方法,确保单例类不能被复制或克隆  
        private function __clone(){}  
        public static function getInstance($host, $username, $password,$database) {  
            //检测类是否被实例化  
            if(!(self::$_instance instanceof self)){  
                self::$_instance=new db($host,$username,$password,$database);  
            }  
            return self::$_instance;  
        }  
        //执行SQL语句  
        public function query($query){  
            return mysql_query($query, $this->link);  
        }  
        //关闭数据库连接  
        public function close(){  
            return mysql_close($this->link);  
        }  
    }  
    //调用单例类测试部分  
    header("Content-type: text/html; charset=utf-8"); //设置网页编码  
    $dbconnector=db::getInstance("localhost","root","root","test");//创建数据库连接类  
    $result=$dbconnector->query("select * from user");//查询数据库  
    for($i=0;$row=mysql_fetch_array($result);$i++){//打印查询结果  
        echo $row[&#39;id&#39;].",".$row[&#39;username&#39;].",".$row[&#39;password&#39;]."<br/>";  
    }    
    ?>
    Copy after login


This ensures that the class There is only one instance of $dbconnector corresponding to db. Another sentence:

##
$dbconnector1
=db::getInstance(
"localhost"
,
"root"
,
"root"
,
"test"
);
//创建数据库连接类
Copy after login

will still return the original one. Creating an instance of $dbconnector, it should be said that operating $dbconnector and $dbconnector1 has the same effect. They are the same thing. No more resources will be allocated on the server's memory to store $dbconnector and $dbconnector1, because db is singleton, so To achieve the purpose of reducing database pressure.

Related recommendations:


Experience in designing database_PHP tutorial

The above is the detailed content of PHP singleton mode designs database and connects to Model class. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template