Understanding Drupal 8 services

Drupal 8 has this concept of services, or reusable PHP objects. The distinguishing feature of services is that their initiation is configurable. In other words, we can configure what type of instance is created and when this instance is created in the code, mostly without changing the code at all.

Drupal 8 services

Image credits

Why is this a big deal? Assume that you are writing a custom Drupal module which handles a lot of transactional e-mail(a fancy term for e-mail sent to an individual based on some action, like if anyone replies to your comment, for instance). You decide to use some transactional e-mail service like Postmark or Mandrill.

The straightforward way to go about this, is to create a wrapper around the respective API offered by the service. What if we want to migrate to another transactional e-mail service, like Amazon SES? Typically, this would involve rewriting the wrapper around this new service and change the service instance to the newer one throughout the codebase. Services aim to solve this "code rewrite" problem. Let's see how we would tackle this using a "Services" approach.

In the services way of doing things, you will expose the transactional e-mail wrapper as a service. This service would be initiated in your module and invoked whenever you want to send e-mail. The e-mail service you use to send mails, its API keys, configuration etc. will be service parameters. Migrating to a new e-mail service would be as simple as rewriting the service configuration. I wouldn't say it is a zero code change, but its a vast improvement over the previous approach.

There are other benefits of using services. Your code becomes easily testable. Want to test your module's e-mail functionality? Swap your service with a test e-mail service and you are done. Easy peasy!

But they seem very similar to PHP objects

Services sound a lot like PHP objects, except that we specify them via configuration, instead of code. But there's more to it than meets the eye. Services are instantiated lazily, which means no service object is created if the service is not invoked. The other difference is, the same object is returned every time you invoke the service instead of creating new instances.

So what are plugins then?

Plugins are reusable objects discoverable by annotations. Though they are similar to services by definition, they differ in many ways. If you want to expose an interface which can exhibit different behaviour, go for a plugin.An example would be image styles. This is detailed here.

In the next post, we shall see how to create a simple Drupal service.