Dependency Injection with Slimframework

Now we are going to learn about implementing dependency injection with slim framework.Before going to the implementation we should know about dependency injection and its features.

Dependency Injection:

Dependency Injection(DI) is simple design pattern to manage the object dependencies. Also greate examples are available for DI across the web.


  • Handle large set of objects
  • Easy to mock objects while doing the unit tesing
  • Lazy load for objects and more…

One of the greate Example:–net-28146
Another one is :

When comes to slimframework, It is very lightweight framework and If you are going to implementing large scale application with slim then you may handle the large set of objects. It is very hard to handle it.

By default slimframework has build-in resource locator and it provides easy way to inject object to slim app.It supports inject values as well as closure functions.

For example:

I wanted to inject my database connection to the slim DI container.So that i can easy to use that object across the application. How to do that?

Documentation :

Another way is to use Pimple. Pimple is lightweight DI container which is developed by Fabien Potencier, The creator of the Symfony framework

You extending the container as per your needs and it could be reusable one.I have worked lot of projects using pimple and it is very easy and more effective way to handle the objects. Also i have written wrapper class to use pimple.

official url :

Example to use Pimple:

inject value 

Inject service

By default, each time you get a service, Pimple returns the same instance of it. If you want a different instance to be returned for all calls, wrap your anonymous function with the factory() method


So you can use one container object to another one.It quite easy to maintain the object denpendency.Here i have added my reusable pimple DI container for slimframework application


How to call this

It is very simple and easy to handle large set of objects.I hope it quite useful.

Thank you . Don’t forgot to share and subscribe for my updates.

Have a good day..