


Use singleton pattern to design a PHP database class_PHP tutorial
Recently, I feel that the website’s database is under a lot of pressure, causing the website’s speed to drop significantly. Because a considerable part of the pages are directly connected to the database to read data, this part of the pages is also changed to use the database singleton class to implement. Now the following class is basically used to connect to the database.
<?php class nmdb { private $link; static private $_instance; // 连接数据库 private function __construct($host, $username, $password) { $this->link = mysql_connect($host, $username, $password); $this->query("SET NAMES 'utf8'", $this->link); //echo mysql_errno($this->link) . ": " . mysql_error($link). "n"; //var_dump($this->link); return $this->link; } private function __clone(){} public static function get_class_nmdb($host, $username, $password) { //$connector = new nmdb($host, $username, $password); //return $connector; if( FALSE == (self::$_instance instanceof self) ) { self::$_instance = new self($host, $username, $password); } return self::$_instance; } // 连接数据表 public function select_db($database) { $this->result = mysql_select_db($database); return $this->result; } // 执行SQL语句 public function query($query) { return $this->result = mysql_query($query, $this->link); } // 将结果集保存为数组 public function fetch_array($fetch_array) { return $this->result = mysql_fetch_array($fetch_array, MYSQL_ASSOC); } // 获得记录数目 public function num_rows($query) { return $this->result = mysql_num_rows($query); } // 关闭数据库连接 public function close() { return $this->result = mysql_close($this->link); } } ?>
The usage of this class is as follows:
$connector = nmdb::get_class_nmdb($host, $username, $password); $connector -> select_db($database);
You can also refer to the following classes:
<?php /* * mysql 单例 */ class mysql{ private $host ='localhost'; //数据库主机 private $user = 'root'; //数据库用户名 private $pwd = ''; //数据库用户名密码 private $database = 'imoro_imoro'; //数据库名 private $charset = 'utf8'; //数据库编码,GBK,UTF8,gb2312 private $link; //数据库连接标识; private $rows; //查询获取的多行数组 static $_instance; //存储对象 /** * 构造函数 * 私有 */ private function __construct($pconnect = false) { if (!$pconnect) { $this->link = @ mysql_connect($this->host, $this->user, $this->pwd) or $this->err(); } else { $this->link = @ mysql_pconnect($this->host, $this->user, $this->pwd) or $this->err(); } mysql_select_db($this->database) or $this->err(); $this->query("SET NAMES '{$this->charset}'", $this->link); return $this->link; } /** * 防止被克隆 * */ private function __clone(){} public static function getInstance($pconnect = false){ if(FALSE == (self::$_instance instanceof self)){ self::$_instance = new self($pconnect); } return self::$_instance; } /** * 查询 */ public function query($sql, $link = '') { $this->result = mysql_query($sql, $this->link) or $this->err($sql); return $this->result; } /** * 单行记录 */ public function getRow($sql, $type = MYSQL_ASSOC) { $result = $this->query($sql); return @ mysql_fetch_array($result, $type); } /** * 多行记录 */ public function getRows($sql, $type = MYSQL_ASSOC) { $result = $this->query($sql); while ($row = @ mysql_fetch_array($result, $type)) { $this->rows[] = $row; } return $this->rows; } /** * 错误信息输出 */ protected function err($sql = null) { //这里输出错误信息 echo 'error'; exit(); } } //用例 $db = mysql::getInstance(); $db2 = mysql::getInstance(); $data = $db->getRows('select * from blog'); //print_r($data); //判断两个对象是否相等 if($db === $db2){ echo 'true'; } ?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The JS singleton pattern is a commonly used design pattern that ensures that a class has only one instance. This mode is mainly used to manage global variables to avoid naming conflicts and repeated loading. It can also reduce memory usage and improve code maintainability and scalability.

Singleton pattern: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.

In software development, we often encounter situations where multiple objects need to access the same resource. In order to avoid resource conflicts and improve program efficiency, we can use design patterns. Among them, the singleton pattern is a commonly used way to create objects, which ensures that a class has only one instance and provides global access. This article will introduce how to use PHP to implement the singleton pattern and provide some best practice suggestions. 1. What is the singleton mode? The singleton mode is a commonly used way to create objects. Its characteristic is to ensure that a class has only one instance and provides

Thinking about thread safety issues of singleton mode in PHP In PHP programming, singleton mode is a commonly used design pattern. It can ensure that a class has only one instance and provide a global access point to access this instance. However, when using the singleton pattern in a multi-threaded environment, thread safety issues need to be considered. The most basic implementation of the singleton pattern includes a private constructor, a private static variable, and a public static method. The specific code is as follows: classSingleton{pr

The Singleton pattern ensures that a class has only one instance and provides a global access point. It ensures that only one object is available and under control in the application. The Singleton pattern provides a way to access its unique object directly without instantiating the object of the class. Example<?php classdatabase{ publicstatic$connection; privatefunc

Introduction PHP design patterns are a set of proven solutions to common challenges in software development. By following these patterns, developers can create elegant, robust, and maintainable code. They help developers follow SOLID principles (single responsibility, open-closed, Liskov replacement, interface isolation and dependency inversion), thereby improving code readability, maintainability and scalability. Types of Design Patterns There are many different design patterns, each with its own unique purpose and advantages. Here are some of the most commonly used PHP design patterns: Singleton pattern: Ensures that a class has only one instance and provides a way to access this instance globally. Factory Pattern: Creates an object without specifying its exact class. It allows developers to conditionally

Extension and customization of singleton mode in PHP framework [Introduction] Singleton mode is a common design pattern, which ensures that a class can only be instantiated once in the entire application. In PHP development, the singleton pattern is widely used, especially in the development and expansion of frameworks. This article will introduce how to extend and customize the singleton pattern in the PHP framework and provide specific code examples. [What is the singleton pattern] The singleton pattern means that a class can only have one object instance and provides a global access point for external use. In PHP development, pass

Application scenarios and thread safety processes of singleton mode in PHP distributed systems Introduction: With the rapid development of the Internet, distributed systems have become a hot topic in modern software development. In distributed systems, thread safety has always been an important issue. In PHP development, the singleton pattern is a commonly used design pattern, which can effectively solve the problems of resource sharing and thread safety. This article will focus on the application scenarios and thread safety processes of the singleton pattern in PHP distributed systems, and provide specific code examples. 1. Singleton mode
