Skip to content

Dev.Pi.service.database

linzongshu edited this page Oct 17, 2015 · 1 revision

Brief

The database service is used to create database entry instance. And then it can be used to operate database. Its usage is:

Pi::service('database')

Relevant documentation are:

APIs

db

db($options = array())

Get Pi\Db\DbGateway instance.

Parameters

  • $options

Can be array or DbGateway instance, if it is DbGateway instance, it will be set permanently for latter use; if value is array, it will be used to create DbGateway instance for the moment; or null value to load service.database.php data to create DbGateway instance.

Examples

$options = [
    'connection' => [
        'dsn' => '...',
        'username' => '...',
        ...
    ],
];
$adapter = new \Zend\Db\Adapter\Adapter($options);
$dbGateway = Pi::service('database')->db($adapter);
$dbGateway = Pi::service('database')->db($options);
$dbGateway = Pi::service('database')->db();

loadDb

loadDb(array $options = array())

Load dbGateway for temporarily use.

Parameters

  • $options

The array value contains connection parameters, or empty to use service.database.php data as default.

Examples

$options = [
    'connection' => [
        'dsn' => '...',
        'username' => '...',
        ...
    ],
];
$dbGateway = Pi::service('database')->loadDb($options);
$dbGateway = Pi::service('database')->loadDb();

connect

connect(DbGateway $db = null)

Connect to server and return connection instance.

Parameters

  • $db

Pi\Db\DbGateway instance.

Examples

$connection = Pi::service('database')->connect();
$connection->query('select * from core_config where id in (1, 2)');
Clone this wiki locally