0

In Apigility

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

(see the REST Service Tutorial in the documentation).

"DB-Connected" services provide Database Settings, where the adapter can be assigned. And every adapter "knows", which credentials to use and which database to connect.

I created a "Code-Connected" REST service and want the versions V1 and V2 to use separate databases. How can this be achieved?

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

0

In order to use multiple DB adapters, one simply need

  1. to create an appropriate configuration block in the (global.php for the generall setting like driver and local.php for the credentials) -- it can be done manually or over the 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. to set this adapter instead of the default Zend\Db\Adapter\Adapter, e.g. using ZfcBase\Mapper (here an example from an application, where the adapter gets set in the factory for the service class; a service is here the layer between the controller/resource and the DB mapper):

[myproject]/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;
    }

}
automatix
  • 14,018
  • 26
  • 105
  • 230