Backend and Infrastructure

Injecting Configuration and Services, and Using Interfaces

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.

We’ve already created our first service and used dependency injection, but one problem with the FriendHarvester is that we’ve hardcoded the SMTP configuration inside of it. What if we wanted to re-use this class with a different configuration? Or what if our beta and production setups use different SMTP servers? Right now, both are impossible! In this tutorial we're going to see how we can also inject configuration or an entire service. In the end we're going to inject the entire SmtpMailer object and build an interface for it. Through this process we'll make our code more flexible, since it will be able to accept any object that implements MailerInterface.