selective-php / test-traits

Test Traits
MIT License
13 stars 2 forks source link

Get PDO instance Cakephp 5 #12

Closed jimgwhit closed 1 year ago

jimgwhit commented 1 year ago

In this issue https://github.com/selective-php/test-traits/issues/10 they show getting the instance via reflection:

PDO::class => function (ContainerInterface $container) {
    $driver = $container->get(Connection::class)->getDriver();

    $class = new ReflectionClass($driver);
    $method = $class->getMethod('getPdo');
    $method->setAccessible(true);

    return $method->invoke($driver);
},

Where would this code be placed and how called to get the PDO instance?

odan commented 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.

jimgwhit commented 1 year ago

@odan I want the PDO instance in Cakephp 5.

odan commented 1 year ago

This is already a working example for the CakePHP 5 (QueryBuilder).

jimgwhit commented 1 year ago

@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....
odan commented 1 year ago

@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

jimgwhit commented 1 year ago

Thanks.