Home  >  Article  >  Backend Development  >  How to implement database connection pool in PHP

How to implement database connection pool in PHP

Guanhui
GuanhuiOriginal
2020-05-14 13:08:494996browse

How to implement database connection pool in PHP

How does PHP implement a database connection pool?

First define a class and declare an attribute as a connection pool; then add data to the pool in the constructor Fill in the connection instance; finally define a take-out method and a put-back method. When taking out, the last connection instance of the connection pool will be popped out of the stack and returned. When put back, the connection instance will be pushed into the last stack of the connection pool.

Example code:

<?php
namespace Db\Connect;

class Pool
{

  protected $size = 10;

  protected $connects = [];

  protected $dbConf = [
    &#39;hostname&#39; => &#39;127.0.0.1&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;123456&#39;,
    &#39;dbname&#39; => &#39;dbname&#39;
  ];

  public function __construct($size = 10, $dbConf = [])
  {
    $this->size = $size;

    $this->dbdbConf = array_merge($this->dbdbConf, $dbdbConf);

    for($index = 1; $index <= $this->size; $index ++) {

        $connect = mysqli_connect(
          $this->dbConf[&#39;hostname&#39;],
          $this->dbConf[&#39;username&#39;],
          $this->dbConf[&#39;password&#39;],
          $this->dbConf[&#39;dbname&#39;]
        );

        array_push($this->connects, $connect);
    }
  }

  public function getConnect()
  {
    if (count($this->connects) <= 0) {
        throw new \ErrorException( "数据库连接池中已无链接资源,请稍后重试!" );
    } else {
        return array_pop($this->connects);
    }

  }

  public function release($connect)
  {
    if (count($this->connects) >= $this->size) {
      throw new \ErrorException("数据库连接池已满");
    } else {
      array_push($this->connects, $connect);
    }
  }

}

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of How to implement database connection pool in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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