PHP Database connection Pooling implementation

Source: Internet
Author: User
Tags connection pooling fread php database

      • Summary
      • Xml
        • Reading configuration Files
          • Easy Way
          • General method
        • PHP parsing xml
          • Configuration file
          • Analytical
      • Database Connection Pool
      • Test
        • Reject requests when too many applications
        • Refused to put in after full
      • Summarize

Summary

The PHP code is always written in a process-oriented way, so it is largely neither canonical nor secure, nor easy to maintain. For code reuse, be prepared to write a set of their own tool library, so that the future when writing the project can be easily used.

Today's implementation is a database connection pool, which is implemented as a configuration file.

Xml

XML as a highly available structured language, as a configuration file is really concise, although compared to the recent configuration file world of Yaml, JSON and other leaders, may be effective data accounted for smaller, but this redundancy has its existence value.

Basically, you can see the functionality of the XML node by reading it. This is why large projects use XML as a configuration file.

Redundancy can be tolerated, but there is no ambiguity or difficulty in maintaining the problem.

In PHP, working with XML files can be a pleasing thing, though, as with Java programs. However, compared to Python processing, the PHP program is not so elegant.

Reading configuration Files

Reading the configuration file is actually reading the file, and then wrapping it. I use the following two ways.

Easy Way

The first time I used this easy way, it was a bit depressing.

$content = file_get_contents("filename.xml");echo$content;

As a result, when using a browser to access the test PHP file, only the content part of the XML is displayed, but the node information is not displayed at all.

Then I specifically looked at the help document, the result of this function is the string is undoubtedly ah. And then the vardump proved it. So also did not think much, also thought this way can automatically filter out the tag tag information of XML.

The last accidental test, opened the source code of the Web page, found that the function does read all the XML information, but the browser will be displayed in the browser to automatically parse. So you can only see the relevant content section.

General method

The usual way is to read the files step by step. The remaining words are consistent with the above-mentioned programmes.

// 读取配置文件内容            $handlefopen("filepath""r");            $contentfread($handle, filesize("filepath"));
PHP parsing xml

Both of these read files are actually prepared for PHP parsing XML. There are a lot of blogs about the way PHP parses XML. There are many ways, like simplexml,xmlreader,dom and so on. But for a smaller XML configuration file, SimpleXML is sufficient.

Configuration file
<?xml version= "1.0" encoding= "UTF-8"?><mysql>    <!--to prevent surprises, please write in this standard order. It doesn't matter, actually.    <host>localhost</host>    <user>Root</user>    <password>123456</password>    <db>Test</db>    <port>3306</Port></mysql>
Analytical
<?php/** * As an essential tool for parsing XML configuration Files */ class xmlutil {     Public Static $dbconfigpath="./db.config.xml"; Public Static  function getdbconfiguration() {        $dbconfig=Array();Try{//Read configuration file Contents            $handle= fopen ( Self::$dbconfigpath,"R");$content= Fread ($handle, FileSize ( Self::$dbconfigpath));//Get the XML document root node to get related database information            $mysql= Simplexml_load_string ($content);//assigns the obtained XML node information to the associative array, which facilitates the next method invocation            $dbconfig[' Host '] =$mysql->host;$dbconfig[' user '] =$mysql->user;$dbconfig[' Password '] =$mysql->password;$dbconfig[' DB '] =$mysql->db;$dbconfig[' Port '] =$mysql->port;//Returns the configuration information as an associative array            return $dbconfig; }Catch(Exception $e) {Throw NewRuntimeException ("<mark> Error reading database configuration file information! </mark><br/> "); }return $dbconfig; }}
Database Connection Pool

For PHP programs, optimization is endless. and the database connection pool is to some extent the role of optimization. It makes every request to the user no need to request a link resource every time, like a database. Instead, it is returned through links in the existing database connection pool, which is a big boost in terms of time and efficiency.

So, here is a simple simulation of the database connection pool implementation. The core is to maintain a "pool".

Take it from the pond and return it to the pond.

<?php/**x * Database tool class design in PHP * Guo Pu * December 23, 2016 * **/Class DBHelper {Private$dbconfig;Private$dbpool; Public$poolsize; Publicfunction__construct($poolsize = -) {if(! file_exists ("./utils.php")) {Throw NewRuntimeException ("The <mark>utils.php file is missing and the configuration file cannot be initialized!" </mark><br/> "); }Else{Require'./utils.php '; }//Initialize profile information$ This->dbconfig = Xmlutil::getdbconfiguration ();//Prepare database connection pool "pseudo queue"$ 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> failed to connect to the database! </mark><br/> "); Array_push ($ This->dbpool, $conn); }    }/** * Get a Database link resource from the database connection pool * * @throws errorexception * @return mixed * *     PublicfunctionGetconn() {if(Count ($ This->dbpool) <=0) {Throw NewErrorexception ("There are no linked resources in the <mark> database connection pool, please retry!</mark> later"); }Else{returnArray_pop ($ This->dbpool); }    }/** * Put the exhausted database link resource back into the database connection pool * * @param Unknown $conn * @throws errorexcep tion * *     PublicfunctionRelease($conn) {if(Count ($ This->dbpool) >= $ This->poolsize) {Throw NewErrorexception ("<mark> database connection pool is full </mark><br/>"); }Else{Array_push ($ This->dbpool, $conn); }    }}
Reject a request when there are too many test requests

When the request database connection is less than 20, the program is fetched directly from the database connection pool.

When the requested database link resource is larger than the upper limit of the database connection pool, it is not provided. and prompts for exceptions.

Refused to put in after full

When the database connection pool is full, if you want to look back on the custom database link resources, it will not support, and error prompts.

Summarize

In retrospect, this experiment mainly designed and implemented a simple database connection pool with object-oriented angle. To some extent, the optimization of PHP code has played a role.

In addition, SimpleXML is used to parse the XML file, as well as the common operation for file read.

PHP database connection pool implementation

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.