Closed jimgwhit closed 1 year ago
This is a DI container definition to get the PDO instance from the Connection object.
Here is a full example with PHI-DI: https://github.com/odan/slim4-skeleton/blob/master/config/container.php#L75-L83
Note that the actual code of the DI container definition depends on your project specific dependencies.
@odan I want the PDO instance in Cakephp 5.
This is already a working example for the CakePHP 5 (QueryBuilder).
@odan the link above is for slim 4. How do I get the PDO instance in cakephp 5?
In earlier versions this also gave the instance:
public static function dbh()
{
try {
$db = ConnectionManager::get('default');
return $db;
} catch (PDOException $e) {
throw new pdoDbException($e);
}
}
Then I could use prepare in a custom class:
$stmt = self::dbh()->prepare($sql);
etc....
@jimgwhit The code (see above) already shows how to get the PDO instance out of the Connection object. You could try to adapt it to your code, because you already have a Connection object in your $db
variable. Note that, the Connection object already supports raw SQL queries. You may therefore don't need to extract the native PDO object for this purpose.
$connection = ConnectionManager::get('default');
$results = $connection->execute('SELECT * FROM articles')->fetchAll('assoc');
It also provides support for parameterized queries:
https://book.cakephp.org/5/en/orm/database-basics.html#executing-queries
Thanks.
In this issue https://github.com/selective-php/test-traits/issues/10 they show getting the instance via reflection:
Where would this code be placed and how called to get the PDO instance?