Skip to content

How to configure/load database in Slim Framework 3

Last updated on February 20, 2018

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 – 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.

 [
        'displayErrorDetails' => true, // set to false in production

        // Renderer settings
        ....
        ....    

        // Monolog settings
        ....
        ....

        // Database connection settings
        "db" => [
            "host" => "localhost",
            "dbname" => "slim3",
            "user" => "root",
            "pass" => ""
        ],
    ],
];

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.

// DIC configuration
$container = $app->getContainer();

...
...
...

// PDO database library
$container['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;
};

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments