How to use database connection pool in PHP?
For PHP programs, optimization never ends. The database connection pool plays an optimization role to a certain extent. This eliminates the need to apply for link resources from the database for each user request. Instead, it is returned through the link in the existing database connection pool, which is a big improvement in terms of time and efficiency. Therefore, this article will lead you to understand how PHP uses database connection pooling?
Related recommendations: What is the search algorithm in PHP array? How to find it?
xml
As a highly available structured language, XML is really concise and comprehensive as a configuration file. Although compared to recent leaders such as YAML and JSON in the configuration file world, the proportion of valid data may be relatively small, but this redundancy has its value.
Basically, you can know its functions after reading the xml nodes. This is why large projects use XML as configuration files.
Redundancy can be tolerated, but it cannot bring any ambiguity or maintenance difficulties.
In PHP, using XML files will be a pleasing thing, although compared to Java programs, this is not the case. But compared to Python processing, PHP programs are not so elegant.
Reading the configuration file
Reading the configuration file actually means reading the file and then packaging it. The following two methods are commonly used by me.
Easy method
The first time I used this simple method, I was really a little depressed.
$content = file_get_contents("filename.xml");echo $content;
As a result, when using a browser to access the php file for testing, only the content of the xml was displayed, but the node information was not displayed at all.
Then I checked the help documentation and found that the result returned by this function is undoubtedly a string. Then vardump also proved this. So I didn't think much about it, thinking that this method could automatically filter out the XML tag TAG information.
The last accidental test was to open the source code of the web page and found that this function did read all the information of XML, but it was automatically parsed by the browser when it was displayed on the browser. So only the relevant content parts can be seen.
Conventional method
The conventional method is to read the file step by step. The rest is consistent with the above plan.
// 读取配置文件内容 $handle = fopen("filepath", "r"); $content = fread($handle, filesize("filepath"));
PHP parses XML
The above two kinds of reading files are actually prepared for PHP to parse XML. There are many blogs about the way PHP parses XML. There are many ways, such as simplexml, XMLReader, DOM and so on. But for smaller xml configuration files, simplexml is enough.
Configuration file
<?xml version="1.0" encoding="UTF-8" ?><mysql> <!-- 为防止出现意外,请按照此标准顺序书写.其实也无所谓了 --> <host>localhost</host> <user>root</user> <password>123456</password> <db>test</db> <port>3306</port></mysql>
Analysis
<?php /** * 作为解析XML配置文件必备工具 */ class XMLUtil { public static $dbconfigpath = "./db.config.xml"; public static function getDBConfiguration() { $dbconfig = array (); try { // 读取配置文件内容 $handle = fopen(self::$dbconfigpath, "r"); $content = fread($handle, filesize(self::$dbconfigpath)); // 获取xml文档根节点,进而获取相关的数据库信息 $mysql = simplexml_load_string($content); // 将获取到的xml节点信息赋值给关联数组,方便接下来的方法调用 $dbconfig['host'] = $mysql->host; $dbconfig['user'] = $mysql->user; $dbconfig['password'] = $mysql->password; $dbconfig['db'] = $mysql->db; $dbconfig['port'] = $mysql->port; // 将配置信息以关联数组的形式返回 return $dbconfig; } catch ( Exception $e ) { throw new RuntimeException ( "<mark>读取数据库配置文件信息出错!</mark><br />" ); } return $dbconfig; }
Database connection pool
For PHP programs, optimization never ends. The database connection pool plays an optimization role to a certain extent. This eliminates the need to apply for link resources from the database for each user request. Instead, it is returned through the link in the existing database connection pool, which is a big improvement in terms of time and efficiency.
So, here is a simple simulation of the implementation of the database connection pool. The core is to maintain a "pool".
Take it from the pool, use it, and return it to the pool.
<?php /**x * PHP中的数据库 工具类设计 * 郭璞 * 2016年12月23日 * **/ class DbHelper { private $dbconfig; private $dbpool; public $poolsize; public function __construct($poolsize = 20) { if (! file_exists ( "./utils.php" )) { throw new RuntimeException ( "<mark>utils.php文件丢失,无法进行配置文件的初始化操作!</mark><br />" ); }else { require './utils.php'; } // 初始化 配置文件信息 $this->dbconfig = XMLUtil::getDBConfiguration (); // 准备好数据库连接池“伪队列” $this->poolsize = $poolsize; $this->dbpool = array (); for($index = 1; $index <= $this->poolsize; $index ++) { $conn = mysqli_connect ( $this->dbconfig ['host'], $this->dbconfig ['user'], $this->dbconfig ['password'], $this->dbconfig ['db'] ) or die ( "<mark>连接数据库失败!</mark><br />" ); array_push ( $this->dbpool, $conn ); } } /** * 从数据库连接池中获取一个数据库链接资源 * * @throws ErrorException * @return mixed */ public function getConn() { if (count ( $this->dbpool ) <= 0) { throw new ErrorException ( "<mark>数据库连接池中已无链接资源,请稍后重试!</mark>" ); } else { return array_pop ( $this->dbpool ); } } /** * 将用完的数据库链接资源放回到数据库连接池 * * @param unknown $conn * @throws ErrorException */ public function release($conn) { if (count ( $this->dbpool ) >= $this->poolsize) { throw new ErrorException ( "<mark>数据库连接池已满</mark><br />" ); } else { array_push ( $this->dbpool, $conn ); } } }
Test
When there are too many applications, the request is rejected
When the number of applications for database connections is less than 20, the program directly connects from the database connection pool obtained from.
#When the requested database link resource is greater than the upper limit of the database connection pool, it will not be provided. and prompt an exception.
Refuse to put in when full
When the database connection pool is full, if you want to return to the customized database link resource, it is not supported. , and an error message is reported.
Summary
To review, this experiment mainly designed and implemented a simple database connection pool from an object-oriented perspective. It plays a role in optimizing PHP code to a certain extent.
In addition, simplexml is simply used to parse XML files and perform common file reading operations.
Related learning video sharing: php video tutorial
The above is the detailed content of How to use database connection pool in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
