Drupal 8 service dependency injection in our custom module

We are going to be learning Drupal 8 service dependency injection and we are going to be building on top of the module that we created in a previous video.

Dependency Injection enables us to decouple reusable functionality by injecting it, rather than creating it inside of a class (in our case service class).

In order to find all the services that we have from Drupal 8 core - we could just search for a service on this page. There we will find the current user service. In order to inject it into our service we just have to take the service name and pass it as an argument in the .services.yml file like this:

services:
    drupalup_service.cow:
        class: Drupal\drupalup_service\CowService
        arguments: ['@current_user']

and then in our service class we just have to get the service in the __construct method and store it in a local variable like this:

<?php

namespace Drupal\drupalup_service;

use Drupal\Core\Session\AccountProxy;

/**
 * CowService is a simple exampe of a Drupal 8 service.
 */
class CowService {

  private $currentUser;
  private $sounds = ["looO", 'mooO'];

  /**
   * Part of the DependencyInjection magic happening here.
   */
  public function __construct(AccountProxy $currentUser) {
    $this->currentUser = $currentUser;
  }

  /**
   * Returns a a Drupal user as an owner.
   */
  public function whoIsYourOwner() {
    return $this->currentUser->getDisplayName();
  }

  /**
   * Returns a cow sound.
   */
  public function saySomething() {
    return $this->sounds[array_rand($this->sounds)];
  }


}

and then we could use the current user service and get the display name of the current logged in user in the whoIsYourOwner method.

The full code of the module you may find here.

Meet the author

Nikolay is a Drupal PHP developer with more than 7 years of experience. Passion for teaching, passion for simplicity and effectiveness of the code are just some keywords that he cares about. See more ...
Drupal Up is a platform for learning Drupal ...

Drupal Dan promoting
The idea is though not just to be another platform with some boring videos but all the videos to be inspired by real-world problems. That means something that you will most probably need if you work with Drupal. We want you to be successful and we want to teach you everything we know about Drupal!
So watch the videos, try to follow and reproduce, ask questions and you will see you will be able to conquer this wonderful sea that Drupal 8 is.