Sunday 3 May 2020

Services injection in custom Controller

In custom controller, if it is extending ControllerBase class then no need to inject (with service container) some of the services explained in this post. ControllerBase already having some of the services which we can directly access in the custom controller without injecting it.

Below example will show how to use those services.

Custom Controller Class code

<?php

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Class ControllerServicesInjectionController.
 *
 * @package Drupal\custom_module\Controller
 */
class ControllerServicesInjectionController extends ControllerBase {

  // Below trait is used to make translatable string in controller class.
  use StringTranslationTrait;

  /**
   * Function having information about services which need not to inject.
   */
  public function useServicesWithoutInjecting() {

// Get current user object without injecting user service.
// Returns the current user.
       $user_object = $this->currentUser();

// Get entityTypeManager service without injecting entityTypeManager service.
// Retrieves the entity type manager.
$entity_type_manager = $this->entityTypeManager();

// Get moduleHandler service without injecting moduleHandler service.
// Returns the module handler.
$module_handler = $this->moduleHandler();

// Get languageManager service without injecting languageManager service.
// Returns the language manager service.
$language_manager = $this->languageManager();

// Get entityFormBuilder service without injecting entityFormBuilder service.
// Retrieves the entity form builder.
$entity_form_builder = $this->entityFormBuilder();

// Get formBuilder service without injecting formBuilder service.
// Returns the form builder service.
$form_builder = $this->formBuilder();

// Get state service without injecting state service.
// Returns the state storage service.
$state_object = $this->state();

// Get keyValue service without injecting keyValue service.
// Returns a key/value storage collection.
$keyvalue_object = $this->keyValue('config_key');

        // Translate string in controller class with StringTranslationTrait.
$this->t('This is translatable string.');

        // To only check the above services output.
        print_r($user_object);
        print_r($entity_type_manager);
        print_r($module_handler);
        print_r($language_manager);
        print_r($entity_form_builder);
        print_r($form_builder);
        print_r($state_object);
        print_r($keyvalue_object);
  }
}