如何在 Slim 4 中注入多个 PDO 实例 [英] How to inject multiple PDO instances in Slim 4

查看:57
本文介绍了如何在 Slim 4 中注入多个 PDO 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 Slim 4(对于 Slim 来说也是全新的),在阅读并阅读了一些文章后,我设法通过 PDO 连接到数据库获得了一个骨架应用程序设置.

I've just started using Slim 4 (also brand new to Slim as a whole) and after reading up and following some articles I've managed to get a skeleton app setup with a PDO connection to the DB.

我现在想注入第二个 PDO 实例,以便可以根据请求使用第二个数据库,尽管我正在努力弄清楚如何做到这一点.

I'm now looking to inject a second PDO instance so that a second database can be used based on the request, though I'm struggling to get my head around how to do this.

我目前的设置是:

settings.php

$settings['db'] = [
    'driver' => 'mysql',
    'host' => 'database',
    'username' => 'root',
    'database' => 'demo',
    'password' => 'password',
    'flags' => [
        // Turn off persistent connections
        PDO::ATTR_PERSISTENT => false,
        // Enable exceptions
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        // Emulate prepared statements
        PDO::ATTR_EMULATE_PREPARES => true,
        // Set default fetch mode to array
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ],
];

container.php

return [
    Configuration::class => function () {
        return new Configuration(require __DIR__ . '/settings.php');
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);
        $app = AppFactory::create();

        return $app;
    },

    PDO::class => function (ContainerInterface $container) {
        $config = $container->get(Configuration::class);

        $host = $config->getString('db.host');
        $dbname =  $config->getString('db.database');
        $username = $config->getString('db.username');
        $password = $config->getString('db.password');
        $dsn = "mysql:host=$host;dbname=$dbname;";

        return new PDO($dsn, $username, $password);
    },

];

代码库中的使用示例

class UserReaderRepository
{
    /**
     * @var PDO The database connection
     */
    private $connection;

    /**
     * Constructor.
     *
     * @param PDO $connection The database connection
     */
    public function __construct(PDO $connection)
    {
        $this->connection = $connection;
    }

    /**
     * Get user by the given user id.
     *
     * @throws DomainException
     *
     * @return array The user data
     */
    public function getUsers(): array
    {
        $sql = "SELECT user_id, title, firstname, surname, email_address FROM user us;";
        $statement = $this->connection->prepare($sql);
        $statement->execute();

据我所知,PDO 类本身在 container.php 中实例化 - 我如何修改它以实例化 2 个单独的 PDO 类 - 以及我稍后如何在存储库中使用它们?

From what I can tell, the PDO class itself is instantiated within container.php - how do i modify this as to instantiate 2 separate PDO classes - and how do i use them within repositories later on?

为清楚起见,我尝试查看如何在 slim 4 中设置和注入多个 PDO 数据库连接?但是我不太明白在哪里定义 PDO 类.我也看过 here 这似乎没有帮助 - 我没有 dependencies.php,我最接近的是 middleware.php 但是当我尝试这个时我得到错误 Uncaught Error: Cannot use object of在/var/www/config/middleware.php 中输入 DI\Container 作为数组:

For clarity, I've tried looking at How to set up and inject multiple PDO database connections in slim 4? but I don't quite understand where to define the PDO classes. I've also looked here which didn't seem to help - I don't have a dependencies.php, the closest I have is middleware.php but when I try this I get the error Uncaught Error: Cannot use object of type DI\Container as array in /var/www/config/middleware.php:

return function (App $app) {
    // Parse json, form data and xml
    $app->addBodyParsingMiddleware();

    // Add global middleware to app
    $app->addRoutingMiddleware();

    $container = $app->getContainer();

    // PDO database library
    $container['db'] = function ($c) {
        $settings = $c->get('settings')['db'];
        $pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
            $settings['user'], $settings['pass']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        return $pdo;
    };

    // Error handler
    $settings = $container->get(Configuration::class)->getArray('error_handler_middleware');
    $display_error_details = (bool)$settings['display_error_details'];
    $log_errors = (bool)$settings['log_errors'];
    $log_error_details = (bool)$settings['log_error_details'];

    $app->addErrorMiddleware($display_error_details, $log_errors, $log_error_details);
};

推荐答案

经过深思熟虑,我想我已经解决了.

After some deliberation I think I've worked it out.

我使用容器来创建 PDO 实例

I used the container to create the PDO instances

$container = $app->getContainer();

    $container->set('db', function(ContainerInterface $c) {
        $config = $c->get(Configuration::class);

        $host = $config->getString('db.host');
        $dbname =  $config->getString('db.database');
        $username = $config->getString('db.username');
        $password = $config->getString('db.password');
        $dsn = "mysql:host=$host;dbname=$dbname;";

        return new PDO($dsn, $username, $password);
    });

    $container->set('db_readonly', function(ContainerInterface $c) {
        $config = $c->get(Configuration::class);

        $host = $config->getString('db_readonly.host');
        $dbname =  $config->getString('db_readonly.database');
        $username = $config->getString('db_readonly.username');
        $password = $config->getString('db_readonly.password');
        $dsn = "mysql:host=$host;dbname=$dbname;";

        return new PDO($dsn, $username, $password);
    });

然后在构造函数中更改存储库以使用App,然后使用容器获取PDO实例

Then changed the repository to use the App within the constructor, then using the container to get the PDO instances

/**
     * @var PDO The database
     */
    private $db;

    /**
     * @var PDO The readonly database
     */
    private $readonly_db;

    /**
     * Constructor.
     *
     * @param App $app The database db
     */
    public function __construct(App $app)
    {
        $container = $app->getContainer();
        $this->db = $container->get('db');
        $this->readonly_db = $container->get('db_readonly');
    }

留在这里以防其他人有问题,但如果有更好的方法来做到这一点,或者我目前的方法可以改进,我会很感激反馈

Leaving this here in case anyone else has issues, although if there's a better way to do it, or my current method can be improved upon, I'd appreciate the feedback

这篇关于如何在 Slim 4 中注入多个 PDO 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆