The DoctrineServiceProvider provides integration with the Doctrine DBAL for easy database access (Doctrine ORM integration is not supplied).
db.options: Array of Doctrine DBAL options.
These options are available:
pdo_mysql
.
Can be any of: pdo_mysql
, pdo_sqlite
, pdo_pgsql
,
pdo_oci
, oci8
, ibm_db2
, pdo_ibm
, pdo_sqlsrv
.pdo_mysql
, and pdo_oci/oci8
,
specifies the charset used when connecting to the database.pdo_sqlite
, specifies the path to
the SQLite database.pdo_mysql
, pdo_pgsql
, and pdo_oci/oci8
,
specifies the port of the database to connect to.These and additional options are described in detail in the Doctrine DBAL configuration documentation.
Doctrine\DBAL\Connection
.Doctrine\DBAL\Configuration
.1 2 3 4 5 6 | $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:
1 | composer require "doctrine/dbal:~2.2"
|
The Doctrine provider provides a db
service. Here is a usage
example:
1 2 3 4 5 6 7 | $app->get('/blog/{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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $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' => 'utf8mb4',
),
'mysql_write' => array(
'driver' => 'pdo_mysql',
'host' => 'mysql_write.someplace.tld',
'dbname' => 'my_database',
'user' => 'my_username',
'password' => 'my_password',
'charset' => 'utf8mb4',
),
),
));
|
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']->fetchAll('SELECT * FROM table');
$app['dbs']['mysql_read']->fetchAll('SELECT * FROM table');
Using multiple connections:
1 2 3 4 5 6 7 8 9 10 | $app->get('/blog/{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.