How to configure multiple databases in zf2

Configuring multiple databases adapters in zf2 is pretty easy. In this post i will show you how to configure and connect to different databases in zf2 application.

Adapter Abstract Service factory(Zend\Db\Adapter\AdapterAbstractServiceFactory) allow us to create multiple DB adapter instances in zf2.

In this example i am adding two extra database adapters apart from the default one, so total database adapter connections are 3 here with primary connection.

After done with configuration changes – test your settings by using IndexController.php controller(find at the end of the post).

config/autoload/local.php
create and configure your database adapter settings.

config/autoload/global.php

1. Register Zend\Db\Adapter\AdapterAbstractServiceFactory at ‘abstract_factories’ under ‘service_manager’ key.
2. configure adapters settings of databases.

Test Controller

Create one Test Controller called IndexController.php in your Application Module. change the table name and then point your browser to

1.localhost…/index.php/index/
2.localhost…/index.php/fromDB1/
3.localhost…/index.php/fromDB2/

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.