nstwf/mysql-connection-pool

Reactphp MySQL connection pool

1.2.0 2023-01-15 19:26 UTC

This package is auto-updated.

Last update: 2024-10-30 15:07:24 UTC


README

CI codecov Packagist Version

Simple connection pool for mysql client using connection

Table of contents

Quickstart example

$pool = new \Nstwf\MysqlConnectionPool\Pool('localhost:3306');

$pool
    ->getConnection()
    ->then(function (\Nstwf\MysqlConnection\ConnectionInterface $connection) use ($pool) {
        $connection->query("UPDATE users SET blocked = 1 WHERE id = 3");
        
        $pool->releaseConnection($connection);
    });

Usage

PoolInterface

The main role of PoolInterface - managing connections with selected options

Options

  • waitForConnections: bool, set up the behavior while no free connections exists and user call getConnection method. If set to false - throws an exception, otherwise return a promise with free connection. (Default: true)
  • connectionLimit: int, the maximum number of connections at the same time. 0 - for unlimited. (Default: 5)
$pool = new \Nstwf\MysqlConnectionPool\Pool('localhost:3306', null, 10, false);

getConnection

The getConnection(): PromiseInterface<ConnectionInterface> method can be used to create a new ConnectionInterface instance if no free connections available, otherwise select one of free

$pool
    ->getConnection()
    ->then(function (\Nstwf\MysqlConnection\ConnectionInterface $connection) {
       $connection->query("UPDATE users SET active = 0 WHERE id = 2");
       $connection->query("UPDATE users SET blocked = 1 WHERE id = 3");
       
       $pool->releaseConnection($connection);
    });

releaseConnection

The releaseConnection(ConnectionInterface $connection): void method can be used to release connection to the pool

$pool->releaseConnection($connection);

query

The query(string $sql, array $params = []): PromiseInterface<QueryResult> method is a shortcut for calls getConnection() -> query() -> releaseConnection()

$pool->query("UPDATE users SET active = 0 WHERE id = ?", [2]);

transaction

The transaction(callable $callable): PromiseInterface method is a shortcut for calls: getConnection() -> transaction() -> releaseConnection():

$pool->transaction(function(\Nstwf\MysqlConnection\ConnectionInterface $connection) {
    $connection->query("UPDATE users SET active = 0 WHERE id = 2");
});

Install

The recommended way to install this library is through Composer. New to Composer?

This project follows SemVer. This will install the latest supported version:

composer require nstwf/mysql-connection

See also the CHANGELOG for details about version upgrades.

It's highly recommended to use PHP 8+ * for this project.

Tests

To run the test suite, you first need to clone this repo and then install all dependencies through Composer:

composer install

To run the test suite, go to the project root and run:

vendor/bin/phpunit

License

MIT, see LICENSE file.