How to connect to multiple Database – Slim Framework.

In the earlier post I wrote a tutorial on “how to connecting to database in slim framework“. In this post, I would like to show you, how you can connect to multiple databases in the same slim framework application.
For single database connection, we have created an instance of the database and injected database object into the container using dependency injection. We gonna follow the same principle to use multiple database connections, the only difference is, we will use the different key in container array.

We are going to modify following files –
src/settings.php – It holds application level configuration details, its just a associative array.
src/dependencies.php – It holds application level dependencies

How to connect to multiple Database

Database configuration settings

Open you settings.php and update with your preferred database configurations,

Database configuration

There are many database libraries available for PHP, but this example uses PDO. Now open your src/dependencies.php file and configure database library as shown below. you can use your own libraries by adapting the example.

In the above code we are injecting database objects into container using dependency injection, called db and blog_db. So now you can access your database objects with $this->db and $this->blog_db in your application, and using this object you can perform operations like create,update,delete,find..etc on database.

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.

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets. Protection Status