How to use PDO in slimfamework 4?

Asked

Viewed 38 times

0

Could someone tell me how I instate PDO in a file in the slim framework using the app->get?

I did in the configuration in the file Settings and dependencies but I do not know how to call the connection in another file to select for example.

use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;

return function (ContainerBuilder $containerBuilder) {
    $containerBuilder->addDefinitions([
        PDO::class => function (ContainerInterface $c) {
            $dbSettings = $c->get('settings')['db1'];
            $dsn = 'mysql:host=' . $dbSettings['host'] . ';dbname=' . $dbSettings['dbname'];
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            return new PDO($dsn, $dbSettings['user'], $dbSettings['pass'], $options);
        },
    ]);
};

1 answer

0

Opa,

How you set up Dependencyinjection, just call in your Action constructor

public function __construct(\PDO $pdo)
{
    // sua lógica aqui
}

Also missing in its configuration the bar before the PDO => PDO, it looks like this:

\PDO::class => function (ContainerInterface $c)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.