librelist archives

« back to archive

[PDP] Configuration of the databases

[PDP] Configuration of the databases

Loic d'Anterroches
2011-07-23 @ 10:02

on my way to code some MongoDB stuff, I am refreshing/implementing the
proposed way to access a database. This is mostly a reminder of what we
decided with the addition of the automatic selection of the database and
thus, it now returns a database handler and not a "server" handler.

So in the case of SQLite you get already a connection open to a given
database, in Mongo you get a MongoDB object (and not a Mongo object).
These are the two drivers implemented in \photon\db. This is very
complex code as you can read:

class MongoDB
    public static function get($def)
        $cfg = array_merge(
                           array('server' => 'mongodb://localhost:27017',
                                 'options' => array('connect' => true),
                                 'database' => 'test'),
        $conn = new \Mongo($cfg['server'], $cfg['options']);

        return $conn->selectDB($cfg['database']);

In the configuration, you put something like:

$cfg = array(
   'databases' => array(
        'mongo' => array(
                         'server' => 'mongodb://',
                         'engine' => '\photon\db\MongoDB',
                         'database' => 'foobar'
        'default' => array(
                         // will use the localhost server
                         'engine' => '\photon\db\MongoDB',
                         'database' => 'bingo'
       'sqlite' => array(
                         'engine' => '\photon\db\SQLite',
                         'database' => '/tmp/db.sqlite'
       'special' => array(
                          'engine' => '\your\app\spcial\Engine',
                          'database' => 'reallyspecial'
                          'options' => array('key' => 'value'),

And then in the code, if you want the 'special' database you do:

$connection = \photon\db\Connection::get('mongo');
$connection = \photon\db\Connection::get(); // 'default'

Again, it is recommended to either use 'yourapp.db' for the handler name
or better, let somebody configure it on the fly:

$cfg = array(
   'mylogapp.db' => 'mongo',

And then in the code:

$connection = \photon\db\Connection::get(Conf::f('mylogapp.db'));

this way, if you do not define the database, it will pick the default
(hopefully a mongo database or it will fail) but you can have multiple
mongo db connection to use one or another, etc.

All the rest, like ORM, ODM, etc. is not covered by Photon. The goal is
just to have consistent configuration and reuse of the database handlers
in the code. The rest is really up to you.