nia/sql-adapter-pdo

使用PDO实现`nia/sql-adapter`组件。该实现允许您将PDO连接分离为只读连接和写入连接。

该软件包的官方仓库似乎已消失,因此该软件包已被冻结。

1.1.0 2016-11-17 07:22 UTC

This package is not auto-updated.

Last update: 2022-03-05 05:42:36 UTC


README

使用PDO实现nia/sql-adapter组件。该实现允许您将PDO连接分离为只读连接和写入连接。

安装

使用Composer要求此软件包。

composer require nia/sql-adapter

测试

运行单元测试,请使用以下命令

$ cd /path/to/nia/component/
$ phpunit --bootstrap=vendor/autoload.php tests/

如何使用

以下示例展示了如何创建一个简单的服务提供者(基于nia/dependencyinjection组件),该服务提供者注册了只读SQL适配器和写入SQL适配器。

/**
 * Sample provider for sql connection adapters.
 */
class SqlAdapterProvider implements ProviderInterface
{

    /**
     *
     * {@inheritDoc}
     *
     * @see \Nia\DependencyInjection\Provider\ProviderInterface::register()
     */
    public function register(ContainerInterface $container)
    {
        // adapter for the read-only database servers (mostly a load balancer with multiple slave servers of a master-slave-replication).
        $readableAdapterFactory = new SharedFactory(new ClosureFactory(function (ContainerInterface $container) {
            $pdo = new PDO(/* ... */);

            return new PdoReadableAdapter($pdo);
        }));

        // adapter for the write-only database server (mostly the master of a master-slave-replication).
        $writeableAdapterFactory = new SharedFactory(new ClosureFactory(function (ContainerInterface $container) {
            $pdo = new PDO(/* ... */);

            return new PdoWriteableAdapter($pdo);
        }));

        $container->registerService(ReadableAdapterInterface::class, $readableAdapterFactory);
        $container->registerService(WriteableAdapterInterface::class, $writeableAdapterFactory);
    }
}


// somewhere in code: reading
// [...]
$statement = $container->get(ReadableAdapterInterface::class)->prepare('SELECT * FROM ...');
$statement->execute();

foreach ($statement as $row) {
    // [...]
}

// somewhere in code: writing
// [...]
$statement = $container->get(WriteableAdapterInterface::class)->prepare('UPDATE table SET field = :value;');
$statement->bind(':value', 'foobar');
$statement->execute();