PHPackages                             gemvc/connection-pdo - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. gemvc/connection-pdo

ActiveLibrary[Database &amp; ORM](/categories/database)

gemvc/connection-pdo
====================

PDO connection adapter for GEMVC framework

1.0.0(5mo ago)01681MITPHPPHP &gt;=8.2

Since Dec 9Pushed 5mo agoCompare

[ Source](https://github.com/gemvc/connection-pdo)[ Packagist](https://packagist.org/packages/gemvc/connection-pdo)[ Docs](https://github.com/gemvc/connection-pdo)[ RSS](/packages/gemvc-connection-pdo/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (1)

[![PDOGEMVC](https://private-user-images.githubusercontent.com/211101824/524022004-3c3f585b-06ad-406f-b3a7-d834d030cf45.jpg?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzU0MjY4NjEsIm5iZiI6MTc3NTQyNjU2MSwicGF0aCI6Ii8yMTExMDE4MjQvNTI0MDIyMDA0LTNjM2Y1ODViLTA2YWQtNDA2Zi1iM2E3LWQ4MzRkMDMwY2Y0NS5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYwNDA1JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MDQwNVQyMjAyNDFaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1iYzM3MTQ4NDczYmFiZGZmYWIwNGMzZmRiN2NhMjNlZGI4ODNhZTVkNDU0NjNjMTVkNjVjZWM1MTFlNGI0M2I1JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.wxtmfNrSqHJ5OARWpkisn5ldCEVJgE5DZzw8ld48PBg)](https://private-user-images.githubusercontent.com/211101824/524022004-3c3f585b-06ad-406f-b3a7-d834d030cf45.jpg?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzU0MjY4NjEsIm5iZiI6MTc3NTQyNjU2MSwicGF0aCI6Ii8yMTExMDE4MjQvNTI0MDIyMDA0LTNjM2Y1ODViLTA2YWQtNDA2Zi1iM2E3LWQ4MzRkMDMwY2Y0NS5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYwNDA1JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MDQwNVQyMjAyNDFaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1iYzM3MTQ4NDczYmFiZGZmYWIwNGMzZmRiN2NhMjNlZGI4ODNhZTVkNDU0NjNjMTVkNjVjZWM1MTFlNGI0M2I1JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.wxtmfNrSqHJ5OARWpkisn5ldCEVJgE5DZzw8ld48PBg)

gemvc/connection-pdo
====================

[](#gemvcconnection-pdo)

[![PHPStan](https://camo.githubusercontent.com/0c49fa291e31615e99d27499530f5afa286fe1a969a28ba3a6cd08dfd1019697/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230392d3845354346393f7374796c653d666c61742d737175617265266c6f676f3d706870)](https://camo.githubusercontent.com/0c49fa291e31615e99d27499530f5afa286fe1a969a28ba3a6cd08dfd1019697/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230392d3845354346393f7374796c653d666c61742d737175617265266c6f676f3d706870)[![Unit Tests](https://camo.githubusercontent.com/d9d6e413e8de8f003bf61af98a894db19c2bfb713a955914e15e116f619d25ff/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f556e697425323054657374732d3130302532352d3238413734353f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974)](https://camo.githubusercontent.com/d9d6e413e8de8f003bf61af98a894db19c2bfb713a955914e15e116f619d25ff/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f556e697425323054657374732d3130302532352d3238413734353f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974)[![Integration Tests](https://camo.githubusercontent.com/aec17db8a7f472b3c673e04d2a57363b4972deddd9ef457b6730a2697be826b9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f496e746567726174696f6e25323054657374732d50617373696e672d3238413734353f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974)](https://camo.githubusercontent.com/aec17db8a7f472b3c673e04d2a57363b4972deddd9ef457b6730a2697be826b9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f496e746567726174696f6e25323054657374732d50617373696e672d3238413734353f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974)[![Class Coverage](https://camo.githubusercontent.com/8d9a7fe4a38d9ba633e01b99fc41a1d6bcfb00fd125c50e026a40ad8cd9b7ad7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f436c617373253230436f7665726167652d3130302532352d3238413734353f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974)](https://camo.githubusercontent.com/8d9a7fe4a38d9ba633e01b99fc41a1d6bcfb00fd125c50e026a40ad8cd9b7ad7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f436c617373253230436f7665726167652d3130302532352d3238413734353f7374796c653d666c61742d737175617265266c6f676f3d706870756e6974)

PDO connection library implementation package for GEMVC framework.

Package Information
-------------------

[](#package-information)

- **Package Name:** `gemvc/connection-pdo`
- **Namespace:** `Gemvc\Database\Connection\Pdo\`
- **Type:** PDO connection implementation package
- **Environment:** Apache/Nginx PHP-FPM (simple connections)
- **Framework-Specific:** ⚠️ No - This package is framework-agnostic (only depends on `connection-contracts`)
- **Depends On:** `gemvc/connection-contracts: ^1.0`

Purpose
-------

[](#purpose)

This package provides PDO connection implementation for GEMVC framework:

1. **`PdoConnection`** - Real implementation that creates actual PDO connections

    - Creates: `new PDO($dsn, $user, $pass)` - **REAL IMPLEMENTATION**
    - Implements: `ConnectionManagerInterface` (from `connection-contracts` package)
    - Used by: Framework's connection management system
    - **Supports multiple database drivers:**
        - **MySQL** (default, primary) - Optimized with MySQL-specific features
        - **SQLite** - Supported for testing and development
        - **Other PDO drivers** - PostgreSQL, etc. (via standard DSN format)
2. **`PdoConnectionAdapter`** - Adapter that wraps PDO instances

    - Wraps: Existing PDO instances (doesn't create them)
    - Implements: `ConnectionInterface` (from `connection-contracts` package)
    - Used by: `PdoConnection` to wrap created PDO instances

It's designed for traditional PHP-FPM environments where each request gets its own PHP process.

Features
--------

[](#features)

- ✅ **Real Implementation:** Creates actual PDO connections (`PdoConnection`)
- ✅ **Adapter:** Wraps PDO instances for contracts (`PdoConnectionAdapter`)
- ✅ **Multi-Driver Support:** MySQL (default), SQLite, and other PDO drivers
- ✅ **MySQL Optimizations:** Charset/collation setup, buffered queries, strict SQL mode
- ✅ Simple PDO connection management
- ✅ Transaction support (begin, commit, rollback)
- ✅ Error handling
- ✅ Connection state tracking
- ✅ Implements `ConnectionManagerInterface` (real implementation)
- ✅ Implements `ConnectionInterface` (adapter)

Installation
------------

[](#installation)

```
composer require gemvc/connection-pdo
```

Dependencies
------------

[](#dependencies)

### Required

[](#required)

- `php >= 8.2`
- `gemvc/connection-contracts: ^1.0` - For `ConnectionInterface`

### Framework Dependencies (Runtime)

[](#framework-dependencies-runtime)

- None - This package only depends on `connection-contracts` package
- Reads environment variables directly from `$_ENV` (no framework helpers needed)

**Note:** This package is framework-agnostic and only depends on `connection-contracts`. The framework should ensure `$_ENV` is populated before using this package.

Usage
-----

[](#usage)

### Using the Real Implementation

[](#using-the-real-implementation)

#### MySQL (Default)

[](#mysql-default)

```
use Gemvc\Database\Connection\Pdo\PdoConnection;

// Set environment variables (or use defaults)
$_ENV['DB_DRIVER'] = 'mysql';
$_ENV['DB_HOST'] = 'localhost';
$_ENV['DB_NAME'] = 'my_database';
$_ENV['DB_USER'] = 'my_user';
$_ENV['DB_PASSWORD'] = 'my_password';

// Get singleton instance (creates actual PDO connection)
$manager = PdoConnection::getInstance();

// Get connection (real implementation creates it, returns ConnectionInterface)
$connection = $manager->getConnection();

// Get underlying PDO instance
$pdo = $connection->getConnection();

// Use PDO directly
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();

// Or use connection interface methods
$connection->beginTransaction();
$connection->commit();
```

#### SQLite (for Testing/Development)

[](#sqlite-for-testingdevelopment)

```
use Gemvc\Database\Connection\Pdo\PdoConnection;

// Set environment for SQLite
$_ENV['DB_DRIVER'] = 'sqlite';
$_ENV['DB_NAME'] = ':memory:'; // or '/path/to/database.db'

// Get connection
$manager = PdoConnection::getInstance();
$connection = $manager->getConnection();
$pdo = $connection->getConnection();

// Use SQLite connection
$pdo->exec('CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)');
```

#### Programmatic Configuration Override (for CLI/Docker)

[](#programmatic-configuration-override-for-clidocker)

For CLI commands in dockerized applications where you need to override database configuration:

```
use Gemvc\Database\Connection\Pdo\PdoConnection;

// Get manager instance
$manager = PdoConnection::getInstance();

// Override configuration programmatically (useful for CLI/docker)
$manager->setConfig([
    'host' => 'mysql-container',  // Override host for docker
    'port' => 3306,
    'database' => 'my_database',
    'username' => 'my_user',
    'password' => 'my_password',
    // Other config keys are optional and will use defaults
]);

// Get connection with overridden config
$connection = $manager->getConnection();

// Reset back to $_ENV if needed
$manager->resetConfig();
```

**Note:** `setConfig()` clears any cached connections and DSN, ensuring new connections use the updated configuration.

### Using the Adapter

[](#using-the-adapter)

```
use Gemvc\Database\Connection\Pdo\PdoConnectionAdapter;
use PDO;

// Create PDO connection (or get from manager)
$pdo = new PDO($dsn, $user, $pass);

// Wrap in adapter for contracts
$adapter = new PdoConnectionAdapter($pdo);

// Use with connection contracts
$connection = $adapter->getConnection(); // Returns PDO object
$adapter->beginTransaction();
$adapter->commit();
```

Architecture
------------

[](#architecture)

This package provides **two components** that work together with `connection-contracts`:

### 1. `PdoConnection` - Real Implementation

[](#1-pdoconnection---real-implementation)

**Creates actual PDO connections:**

- Creates: `new PDO($dsn, $user, $pass)` - **REAL IMPLEMENTATION**
- Implements: `ConnectionManagerInterface` (from `connection-contracts` package)
- Manages connection lifecycle
- Handles configuration from environment variables
- Returns: `ConnectionInterface` (wrapped PDO via `PdoConnectionAdapter`)
- Simple connection caching (one connection per name, within request)
- No framework dependencies - reads `$_ENV` directly

**Database Driver Support:**

- **MySQL** (default): Primary driver with optimizations (charset, collation, strict mode)
- **SQLite**: Supported for testing/development (uses `:memory:` or file path)
- **Other PDO drivers**: PostgreSQL, etc. (via standard DSN format)

**Configuration Methods:**

1. **Environment Variables** (default): Reads from `$_ENV`
2. **Programmatic Override**: Use `setConfig()` method to override programmatically (useful for CLI/docker)

**Environment Variables:**

- `DB_DRIVER` - Database driver (default: `mysql`, supports: `mysql`, `sqlite`, `pgsql`, etc.)
- `DB_HOST` - Database host (default: `localhost`, not used for SQLite)
- `DB_PORT` - Database port (default: `3306`, not used for SQLite)
- `DB_NAME` - Database name (default: `gemvc_db`, for SQLite use `:memory:` or file path)
- `DB_USER` - Database username (default: `root`, not used for SQLite)
- `DB_PASSWORD` - Database password (default: empty, not used for SQLite)
- `DB_CHARSET` - Database charset (default: `utf8mb4`, MySQL only)
- `DB_COLLATION` - Database collation (default: `utf8mb4_unicode_ci`, MySQL only)
- `DB_PERSISTENT_CONNECTIONS` - Enable persistent connections (default: `1` - enabled, MySQL only)
- `DB_CONNECTION_TIMEOUT` - Connection timeout in seconds (default: `5`, MySQL only)
- `APP_ENV` - Application environment (optional, used for dev logging)

**Programmatic Configuration Methods:**

- `setConfig(array $config): void` - Override configuration programmatically
    - Clears cached connections and DSN
    - Useful for CLI commands in dockerized applications
    - All config keys are optional (uses defaults if not provided)
    - Example: `$manager->setConfig(['host' => 'mysql-container', 'database' => 'my_db'])`
- `resetConfig(): void` - Reset configuration back to `$_ENV` values

### 2. `PdoConnectionAdapter` - Adapter

[](#2-pdoconnectionadapter---adapter)

**Wraps existing PDO instances:**

- Wraps: Existing PDO instances (doesn't create them)
- Implements: `ConnectionInterface` (from `connection-contracts` package)
- Provides transaction management (on Connection, not Manager)
- Error handling and state tracking
- Used by: `PdoConnection` to wrap created PDO instances

### Complete Flow

[](#complete-flow)

```
Application/Framework:
  PdoConnection::getInstance()
    └─> Returns: PdoConnection (singleton)
        └─> getConnection() creates: new PDO($dsn, $user, $pass)  ← REAL IMPLEMENTATION
            └─> Wraps PDO with: PdoConnectionAdapter
                └─> Returns: ConnectionInterface

Package Structure:
  PdoConnection (ConnectionManagerInterface)
    └─> Creates: PDO instances
    └─> Wraps with: PdoConnectionAdapter
        └─> Returns: ConnectionInterface

Contracts Package:
  ConnectionManagerInterface (from connection-contracts)
    └─> Implemented by: PdoConnection
    └─> Returns: ConnectionInterface (from connection-contracts)

```

### Integration with connection-contracts

[](#integration-with-connection-contracts)

- **`PdoConnection`** implements `ConnectionManagerInterface` (from contracts)
- **`PdoConnectionAdapter`** implements `ConnectionInterface` (from contracts)
- **Result:** Complete implementation of connection contracts, framework-agnostic

Testing
-------

[](#testing)

### Running Tests

[](#running-tests)

```
composer install
vendor/bin/phpunit
vendor/bin/phpstan analyse --level 9
```

### Test Coverage

[](#test-coverage)

The package includes comprehensive test coverage:

- **Overall Coverage:** 100.00% lines, 100.00% methods
- **PdoConnection:** 100.00% lines, 100.00% methods
- **PdoConnectionAdapter:** 100.00% lines, 100.00% methods
- **Total Tests:** 145 tests with 410 assertions

### Test Classes

[](#test-classes)

- **PdoConnectionTest** - Unit tests for `PdoConnection` (isolated testing)
- **PdoConnectionClassTest** - Comprehensive test class covering all methods
- **PdoConnectionIntegrationTest** - Integration tests with real database operations
- **PdoConnectionAdapterTest** - Unit tests for `PdoConnectionAdapter`
- **PdoConnectionAdapterIntegrationTest** - Integration tests for adapter

### Generating Coverage Report

[](#generating-coverage-report)

```
# Generate HTML coverage report
vendor/bin/phpunit --coverage-html coverage-report --coverage-filter src

# View text coverage summary
vendor/bin/phpunit --coverage-text --coverage-filter src
```

The HTML report will be generated in the `coverage-report/` directory.

License
-------

[](#license)

MIT

---

Made with ❤️ by Ali Khorsandfard
--------------------------------

[](#made-with-️-by-ali-khorsandfard)

This package is part of the [GEMVC Repository](https://github.com/gemvc) framework ecosystem.

[GEMVC is PHP framework built for Microservice.](https://www.gemvc.de)

###  Health Score

38

—

LowBetter than 84% of packages

Maintenance78

Regular maintenance activity

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

151d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e56aef71be22058cb4009cb1ef3b656232c2250df6726d63a812e18fe6f73e3c?d=identicon)[gemvc](/maintainers/gemvc)

---

Top Contributors

[![gemvc](https://avatars.githubusercontent.com/u/211101824?v=4)](https://github.com/gemvc "gemvc (7 commits)")

---

Tags

databasepdophp-fpmConnectiongemvc

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/gemvc-connection-pdo/health.svg)

```
[![Health](https://phpackages.com/badges/gemvc-connection-pdo/health.svg)](https://phpackages.com/packages/gemvc-connection-pdo)
```

###  Alternatives

[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k578.4M5.6k](/packages/doctrine-dbal)[ifsnop/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k5.5M68](/packages/ifsnop-mysqldump-php)[nette/database

💾 Nette Database: layer with a familiar PDO-like API but much more powerful. Building queries, advanced joins, drivers for MySQL, PostgreSQL, SQLite, MS SQL Server and Oracle.

5656.7M231](/packages/nette-database)[dibi/dibi

Dibi is Database Abstraction Library for PHP

5013.8M120](/packages/dibi-dibi)[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4572.9M34](/packages/aura-sqlquery)[envms/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

925511.7k13](/packages/envms-fluentpdo)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
