How to create services in Drupal 8

Services are used to handle the operations in reusable way. Services are the core part of dependency injection in Drupal 8. Dependency injection is the technique where by one object supplies the dependencies of other objects. Services are decoupled ie, changes made to one system will not affect to any other systems that bounds to.

The following will describe how to create services:

I am using the module name hellorandom for describing this.

We are going to create a service to print  a  random number between 1 and 100. Here we are using PHP built in function mt_rand() to return random value. Our purpose is to learn how to create service. so the demonstration should simple and elegant.

Create  hellorandom.services.yml file in the route directory of your module folder

services:
  hellorandom.simplerandom:
    class: Drupal\hellorandom\SimpleRandom

Here we are declaring a service called simplerandom. The services functionality contains in a class SimpleRandom.

More details can be found in https://www.drupal.org/docs/8/api/services-and-dependency-injection/structure-of-a-service-file

Create a class called SimpleRandom in modulefolder/src/SimpleRandom.php

namespace Drupal\hellorandom;

class SimpleRandom {

  public function getRandom() {
        return mt_rand(1,100);
    }

}

Well done!. We have created our simplerandom service.

Next step is to call this service from a controller.

We can this service simple using global Drupal class. 

$service = \Drupal::service('hellorandom.simplerandom'); 

But this is not the right way to implement dependency injection. We can see how a controller call service through dependency injection.

Our controller name is SimpleRandomController

namespace Drupal\hellorandom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\hellorandom\SimpleRandom;
use Symfony\Component\DependencyInjection\ContainerInterface;


class SimpleRandomController extends ControllerBase {

    protected $simplerandom;

    public function __construct(SimpleRandom $simplerandom) {
        $this->simplerandom = $simplerandom;
    }

    public static function create(ContainerInterface $container) {
        return new static($container->get('hellorandom.simplerandom'));
    }

}

Here create() method is a factory method. The controller gets instantiated via create() method and container is passed to it.