Package · cdo

Installation & requirements

What you need to install, which PDO driver extension to enable for your database, and the one config class that turns credentials into a live CDO connection.

Requirements

  • PHP ≥ 8.3
  • ext-pdo — the PDO core
  • psr/log ^3.0 — for the logger interface (installed automatically by Composer)

Plus the PDO driver extension for the database you connect to:

Database PHP extension getDriver() returns
PostgreSQL pdo_pgsql pgsql
MySQL / MariaDB pdo_mysql mysql
Oracle pdo_oci oci

Check which drivers are enabled with:

bash
php -m | grep pdo

MySQL vs MariaDB

There is one pdo_mysql extension for both. CDO tells them apart at runtime from the server version string, because MariaDB supports INSERT ... RETURNING and MySQL does not — see Driver detection.

Install

bash
composer require flytachi/winter-cdo

The package autoloads under the Flytachi\\Winter\\Cdo\\ namespace (PSR-4).

Define a config class

A config class describes one connection. Extend the base for your database and fill in credentials inside setUp() — it is called once, right after the object is instantiated.

app/Db/AppDb.php
<?php

namespace App\Db;

use Flytachi\Winter\Cdo\Config\PgDbConfig;

class AppDb extends PgDbConfig
{
  public function setUp(): void
  {
      $this->host     = getenv('DB_HOST') ?: 'localhost';
      $this->port     = (int) (getenv('DB_PORT') ?: 5432);
      $this->database = getenv('DB_NAME') ?: 'myapp';
      $this->username = getenv('DB_USER') ?: 'postgres';
      $this->password = getenv('DB_PASS') ?: '';
  }
}

For MySQL/MariaDB extend MySqlDbConfig instead (default port 3306). The full list of config bases, their defaults, and the inline PgDbCall / MySqlDbCall / DbCall constructors is in the Configuration reference.

Debug mode

Set the DEBUG environment variable to a truthy value to open connections with PDO::ERRMODE_EXCEPTION. CDO already surfaces failures as CDOException, so this is mainly useful while developing.

Get a connection

ConnectionPool instantiates each config once per process and returns a live CDO:

php
use Flytachi\Winter\Cdo\ConnectionPool;
use App\Db\AppDb;

$cdo = ConnectionPool::db(AppDb::class);

Verify it works

ping() runs a SELECT 1 and returns a boolean; pingDetail() adds latency:

php
$config = ConnectionPool::getConfigDb(AppDb::class);

var_dump($config->ping());        // bool
print_r($config->pingDetail());   // ['status' => bool, 'latency' => float|null, 'error' => string|null]

Next steps