PHP code example of flytachi / winter-cpool

1. Go to this page and download the library: Download flytachi/winter-cpool library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

flytachi / winter-cpool example snippets


use Flytachi\Winter\CPool\ConnectionFactory;

final class PdoFactory implements ConnectionFactory
{
    public function __construct(private readonly string $dsn) {}

    public function create(): object
    {
        return new PDO($this->dsn, options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    }

    public function validate(object $connection): bool
    {
        try {
            $connection->query('SELECT 1');
            return true;
        } catch (Throwable) {
            return false;           // dead → the pool retires it and opens a fresh one
        }
    }

    public function close(object $connection): void
    {
        // PDO closes on dereference; other drivers may need an explicit call
    }
}

use Flytachi\Winter\CPool\{ConnectionPool, PoolPolicy};

$pool = new ConnectionPool(new PdoFactory($dsn), new PoolPolicy(maximumPoolSize: 10));

$entry = $pool->borrow();               // a live connection, or throws within connectionTimeout
try {
    /** @var PDO $pdo */
    $pdo = $entry->resource;
    $pdo->query('SELECT now()');
} finally {
    $pool->release($entry);             // always return it — a leaked entry shrinks the pool
}

use Flytachi\Winter\CPool\SingleConnection;

$single = new SingleConnection(new PdoFactory($dsn));

$pdo = $single->get();      // opens on first call
$pdo = $single->get();      // the same object, revalidated when it has been idle

$pool->abandon();   // drop every pooled connection WITHOUT closing it, stop the housekeeper
$pool->close();     // the normal path: close everything and stop the housekeeper

$pool->stats();   // ['total' => 2, 'idle' => 2, 'active' => 0, 'maximum' => 10]