The DoctrineServiceProvider provides integration with the Doctrine DBAL for easy database access.
Note
There is only a Doctrine DBAL. An ORM service is not supplied.
db.options: Array of Doctrine DBAL options.
These options are available:
These and additional options are described in detail in the Doctrine DBAL configuration documentation.
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_sqlite',
'path' => __DIR__.'/app.db',
),
));
Note
Doctrine DBAL comes with the “fat” Silex archive but not with the regular one. If you are using Composer, add it as a dependency to your composer.json file:
"require": {
"doctrine/dbal": "2.2.*",
}
The Doctrine provider provides a db service. Here is a usage example:
$app->get('/blog/show/{id}', function ($id) use ($app) {
$sql = "SELECT * FROM posts WHERE id = ?";
$post = $app['db']->fetchAssoc($sql, array((int) $id));
return "<h1>{$post['title']}</h1>".
"<p>{$post['body']}</p>";
});
The Doctrine provider can allow access to multiple databases. In order to configure the data sources, replace the db.options with dbs.options. dbs.options is an array of configurations where keys are connection names and values are options:
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'dbs.options' => array (
'mysql_read' => array(
'driver' => 'pdo_mysql',
'host' => 'mysql_read.someplace.tld',
'dbname' => 'my_database',
'user' => 'my_username',
'password' => 'my_password',
'charset' => 'utf8',
),
'mysql_write' => array(
'driver' => 'pdo_mysql',
'host' => 'mysql_write.someplace.tld',
'dbname' => 'my_database',
'user' => 'my_username',
'password' => 'my_password',
'charset' => 'utf8',
),
),
));
The first registered connection is the default and can simply be accessed as you would if there was only one connection. Given the above configuration, these two lines are equivalent:
$app['db']->fetchAssoc('SELECT * FROM table');
$app['dbs']['mysql_read']->fetchAssoc('SELECT * FROM table');
Using multiple connections:
$app->get('/blog/show/{id}', function ($id) use ($app) {
$sql = "SELECT * FROM posts WHERE id = ?";
$post = $app['dbs']['mysql_read']->fetchAssoc($sql, array((int) $id));
$sql = "UPDATE posts SET value = ? WHERE id = ?";
$app['dbs']['mysql_write']->executeUpdate($sql, array('newValue', (int) $id));
return "<h1>{$post['title']}</h1>".
"<p>{$post['body']}</p>";
});
For more information, consult the Doctrine DBAL documentation.