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.

0 0 vote
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
zb f
zb f
3 years ago

This is useful to me

2 years ago

Maybe I’m wrong but with this code, you will create a connection after each call of
no ?

patrice flahault
patrice flahault
1 year ago


I don’t understand how you can use $this->db in a repository.
I get an error, unknown $db

class ObContactRepository
public function findByEmail(string $email)
if (empty($email))
return false;

return $this->db
->query('SELECT * FROM ob_contact WHERE email=:email')
->execute([':email' => $email])
} Protection Status
Would love your thoughts, please comment.x