如何在 Apigility 中为多个版本设置不同的数据库/数据库适配器?

How to set up different databases / database adapters for multiple versions in Apigility?

敏捷

DB-Connected services allow [...] to specify a database adapter [...]

(请参阅文档中的 REST Service Tutorial)。

"DB-Connected"服务提供Database Settings,这里可以分配适配器。以及每个适配器 "knows",要使用哪些凭证以及要连接哪个数据库。

我创建了一个 "Code-Connected" REST 服务并希望版本 V1V2 使用单独的数据库。如何实现?

为了使用多个数据库适配器,一个只需要

  1. 在(global.php 中创建适当的配置块(global.php 用于一般设置,如 driverlocal.php 用于凭据)——可以手动或通过 Apugility 完成GUI (Dashboard -> Database Adapters)

global.php

return array(
    'db' => array(
        'adapters' => array(
            'DB\myapi_v1' => array(
                'driver' => 'Pdo',
                'driver_options' => array(
                    1002 => 'SET NAMES \'UTF8\'',
                ),
                'pdodriver' => 'mysql',
            ),
            'DB\myapi_v2' => array(
                ...
            ),
        ),
    ),
    ...
);

local.php

return array(
    'db' => array(
        'adapters' => array(
            'DB\myproject_v1' => array(
                'username' => 'root',
                'password' => 'pwd',
                'dbname' => 'myproject_v1',
                'host' => 'localhost',
            ),
            'DB\myproject_v2' => array(
                ...
            ),
        ),
    ),
    ...
);
  1. 设置此适配器而不是默认的 Zend\Db\Adapter\Adapter,例如使用 ZfcBase\Mapper(这里是应用程序的示例,其中适配器在工厂中设置为 service class;service 是 [=21 之间的层=]/resourceDB mapper):

[我的项目]/module/Portfolio/src/Portfolio/V1/Rest/Image/ImageServiceFactory.php

namespace Portfolio\V1\Rest\Image;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ImageServiceFactory implements FactoryInterface {

    public function createService(ServiceLocatorInterface $serviceManager) {
        $mapper = new ImageMapper;
        $mapper->setDbAdapter($serviceManager->get('DB\myproject_v1'));
        $mapper->setEntityPrototype($serviceManager->get('Portfolio\V1\Rest\Image\ImageEntity'));
        $mapper->getHydrator()->setUnderscoreSeparatedKeys(false);
        $service = new ImageService();
        $service->setMapper($mapper);
        return $service;
    }

}