欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP如何实现数据库连接池

程序员文章站 2022-03-13 11:29:22
...
PHP如何实现数据库连接池

PHP如何实现数据库连接池

首先定义一个类并声明一个属性作为连接池子;然后在构造方法中向池子进行填充连接实例;最后再定义一个取出方法和放回方法,取出时将连接池最后一个连接实例进行出栈并返回,放回时将连接实例压入连接池末栈即可。

实例代码:

<?php
namespace Db\Connect;

class Pool
{

  protected $size = 10;

  protected $connects = [];

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

  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['hostname'],
          $this->dbConf['username'],
          $this->dbConf['password'],
          $this->dbConf['dbname']
        );

        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);
    }
  }

}

推荐教程:《PHP教程

以上就是PHP如何实现数据库连接池的详细内容,更多请关注其它相关文章!

相关标签: php mysql