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.
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.
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.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.