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 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 – https://github.com/slimphp/Slim-Skeleton.

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 container using dependency injection, in this case called db. So now you can access your database object with $this->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.

Arjun
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.
  • Pingback: Slim framework 3 - Route Groups - ArjunPHP.com()

  • Juan Manuel Rivera

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

    • 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’]);

      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

      return $pdo;

      };

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