Thursday 14 March 2019

Service, Service Container, Dependency Injection Drupal 8

Service, Service Container, Dependency Injection

Service 

  • A service is a class(defined by module or core) that provides the reusable functionality. 
  • Services are like accessing the database, sending email, or translating user interface text.
  • Defining service means giving it a name and designating a default class.

Service Container

  • Services are collected into Dependency Injection Container OR service container.
  • This is global object created and contained by kernel during request handling.

Dependency Injection

  • Dependency Injection is also known as a container to efficiently manage services.
  • It is preferred method to access and use services rather than calling global service container. 
  • Services are passed as arguments OR injected via setter method.

Some of the places where we can use dependency injection. Like In creating custom form, in creating custom block, in creating custom rest resource etc.

Services can be injected by 2 ways.
  1. Inject services in class with the help of dependency injection by implementing create() method.
  2. Create modulename.services.yml file and pass services there as arguments and these services(arguments) will be available in class constructor method.
To inject database service in form class, follow bellow steps.
  • Copy and paste "use Symfony\Component\DependencyInjection\ContainerInterface;" statement before class name. This is class to dependency injection.
  • Create protected variable to database connection  as shown below
     /**
       * Database connection object.
       *
       * @var Drupal\Core\Database\Connection
       */
       protected $database;
  • Now use another class with the help of "use" statement. use Drupal\Core\Database\Connection;
  • Now create static create method: 
      /**
        * {@inheritdoc}
        */
        public static function create(ContainerInterface $container) {
          // Instantiates this form class.
          return new static (
            // Load the service required to construct this class.
            $container->get('database')
           );
        }
  • Now create constructor method for the class.
            /**
      * Class constructor.
      */
      public function __construct(Connection $database) {
        $this->database = $database;
      }
  • Now use the above injected database service with below syntax
         $this->database

See inject service in Form, Block, Rest resource with dependency injection.

No comments:

Post a Comment