How to configure/load database in Slim Framework 3

Slim is a full-featured, open-source PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. It comes with a sophisticated URL dispatcher and middleware architecture that makes it ideal for static websites or API prototyping. It supports all(GET, POST, PUT, DELETE) the HTTP methods.

In this tutorial I would like to show you, configuring database settings and injecting database library into the slim container using dependency injection technique.

This post is part of a series called – Getting Started with Slim Framework 3
How to install Slim Framework 3
Slim Framework 3 – Route Groups
Slim Framework 3 – configure/load database in Slim Framework 3

Note: This tutorial assuming that you are using Slim’s Slim-Skeleton application. Here you can find the skeleton application –

Database configuration

First thing first lets open src/settings.php file and configure database connection details to the settings array as shown below.

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 object into the container using dependency injection, in this case, called db. So now you can access your database object with $this->db in your application, and use this object to 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
Juan Manuel Rivera
Juan Manuel Rivera
3 years ago

Hi, how i can to work with 2 or more databases, and how i can use it with the models, thanks !!

3 years ago

Just create another key in the container –

$container[‘second_db’] = function ($c) {

$settings = $c->get(‘settings’)[‘db’];

$pdo = new PDO(“mysql:host=” . $settings[‘host’] . “;dbname=” . $settings[‘dbname’],

$settings[‘user’], $settings[‘pass’]);



return $pdo;


So now you can access your database object with $this->second_database

3 years ago
Guntoro, Ade
Guntoro, Ade
1 year ago

will it work with new version ?

1 month ago

is this work with postgresql database..?


[…] If you are looking for Slim Framework 3, follow the link How to configure/load database in Slim Framework 3 […] Protection Status
Would love your thoughts, please comment.x