Backend and Infrastructure

Introduction to Dependency Injection

This page is archived

We're keeping this page up as a courtesy to folks who may need to refer to old instructions. We don't plan to update this page.

Sprout Video

Note: This is a PHP-based introduction to dependency injection as a concept. It doesn't use a Drupal-specific example. Also, the library it does use, Pimple, is no longer maintained.

Sharpen your object-oriented skills by exploring the ideas and reasons behind dependency injection. This simple principle separates developers who write functional code from those that are able to build great, and maintanable applications. In this series, we'll see dependency injection in action, why it's important, and how it relates to services and service-oriented architecture. We'll also refactor our demo application to use a dependency injection container, using a fantastic—but simple—container called Pimple.

In this tutorial, we’ll be coding with a real example where we create a simple app to help people give their money away, we’re calling it SendMoneyToStrangers.com. We’ve already bootstrapped a small app, which you can download and use if you want to follow along. It uses an SQLite database, so if you don't have that set up, you can grab the database and find installation instructions on the SQLite site. Once you SQLite, you will install the app from the demo code we are providing. We will also be using Composer to make it easier to get Pimple when we need it. If you are not familiar with Composer, you can watch the short tutorial The Wonderful World of Composer to get up and running.

Additional resources

SQLite site
The Wonderful World of Composer tutorial
Pimple