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.