Germania KG · Databases
Pimple Service Provider for creating PDO handlers., (*1)
, (*2)
Installation with Composer
$ composer require germania-kg/databases
Setup
<?php
use Germania\Databases\DatabasesServiceProvider;
// A. Use with Slim or Pimple
$app = new \Slim\App;
$dic = $app->getContainer();
$dic = new Pimple\Container;
// B. Register Service Provider.
// see https://pimple.symfony.com/#extending-a-container
// Optionally pass custom PDO error mode
$dic->register( new DatabasesServiceProvider );
$dic->register( new DatabasesServiceProvider( \PDO::ERRMODE_EXCEPTION ) );
Services
PDO.Factory
Factory callable for PDO handlers. Just have some database credentials at hand., (*3)
<?php
$db = [
'dsn' => "mysql:host=localhost;dbname=MyDatabase;charset=utf8",
'user' => "username",
'pass' => "secret"
];
// Grab Factory
$pdo_factory = $dic['PDO.Factory'];
// Create handler
$pdo = $pdo_factory( $db );
$pdo = $pdo_factory( (object) $db ); // StdClass objects
$pdo = $pdo_factory( new \ArrayObject($db) ); // ArrayAccess instance
Exceptions
The factory accepts an array, ArrayAccess instance or a StdClass object. If the factory parameter passed does not match any of these, an \InvalidArgumentException will be thrown, (*4)
PDO.ErrorMode
The default error mode has been set on Service provider instantiation. You may override it at runtime by extending the service definition:, (*5)
$dic->extend(PDO.ErrorMode', function($default_error_mode, $dic) {
return \PDO::ERRMODE_SILENT;
});
PDO.Options
This service returns the PDO options to use on PDO handler instantiation. By default this is an array with the PDO.ErrorMode shown above., (*6)
$pdo_options = $dic['PDO.Options'];
Overriding
Just extend the service definition. See PHP manual: class PDO for valid options., (*7)
$dic->extend('PDO.Options', function($default_options, $dic) {
return array_merge( $default_options, array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_SILENT
// custom values here
));
});
Development
$ git clone https://github.com/GermaniaKG/Databases.git
$ cd Databases
$ composer install
Unit tests
Either copy phpunit.xml.dist to phpunit.xml and adapt to your needs, or leave as is. Run PhpUnit test or composer scripts like this:, (*8)
$ composer test
# or
$ vendor/bin/phpunit