Skip to content

Instantly share code, notes, and snippets.

@morozov
Created November 6, 2021 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morozov/aef49beb45ff998c37d9598c6db6d9c5 to your computer and use it in GitHub Desktop.
Save morozov/aef49beb45ff998c37d9598c6db6d9c5 to your computer and use it in GitHub Desktop.
External PDO driver middleware for Doctrine DBAL
<?php
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\API\ExceptionConverter;
use Doctrine\DBAL\Driver\PDO\Connection as PDOConnection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class Driver implements DriverInterface
{
/** @var DriverInterface */
private $driver;
/** @var PDO */
private $pdo;
public function __construct(DriverInterface $driver, PDO $pdo)
{
$this->driver = $driver;
$this->pdo = $pdo;
}
public function connect(array $params)
{
// this is where we use our own PDO instance instead of calling the underlying driver
return new PDOConnection($this->pdo);
}
public function getDatabasePlatform()
{
return $this->driver->getDatabasePlatform();
}
public function getSchemaManager(Connection $conn, AbstractPlatform $platform)
{
return $this->driver->getSchemaManager($conn, $platform);
}
public function getExceptionConverter(): ExceptionConverter
{
return $this->driver->getExceptionConverter();
}
}
<?php
use Acme\Middleware;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
require 'vendor/autoload.php';
$pdo = new class ('sqlite::memory:') extends PDO
{
public function query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
{
echo 'Hello from the custom PDO instance!', PHP_EOL;
return parent::query($query, $fetchMode, ...$fetchModeArgs);
}
};
// register our middleware in the connection configuration
$configuration = (new Configuration())->setMiddlewares([new Middleware($pdo)]);
// even though we have instantiated PDO, we still need to tell the driver manager
// which driver it should use to work with the connection
$connection = DriverManager::getConnection(['driver' => 'pdo_sqlite'], $configuration);
// Go!
echo $connection->fetchOne('SELECT 1'), PHP_EOL;
// Hello from the custom PDO instance!
// 1
<?php
use Acme\Driver;
use Doctrine\DBAL\Driver as DriverInterface;
use Doctrine\DBAL\Driver\Middleware as MiddlewareInterface;
class Middleware implements MiddlewareInterface
{
/** @var PDO */
private $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function wrap(DriverInterface $driver): DriverInterface
{
return new Driver($driver, $this->pdo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment