germania-kg / databases
Requires
- php: ^5.6|^7.0
- pimple/pimple: ^3.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.0
- phpunit/dbunit: ^2.0|^3.0
- phpunit/phpunit: ^5.7|^6.0
This package is auto-updated.
Last update: 2024-11-29 05:21:05 UTC
README
Pimple Service Provider for creating PDO handlers.
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.
<?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
PDO.ErrorMode
The default error mode has been set on Service provider instantiation. You may override it at runtime by extending the service definition:
$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.
$pdo_options = $dic['PDO.Options'];
Overriding
Just extend the service definition. See PHP manual: class PDO for valid options.
$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:
$ composer test # or $ vendor/bin/phpunit