Creating a custom service

A simple Drupal 8 example service converting a string to uppercase. 

custom_service.info.yml:

name: Custom service
core: 8.x
type: module

For demonstration purpose only we'll define a route and a controller so we can see our service in action in the end.

custom_service.routing.yml:

custom_service.demo:
  path: '/custom_service-demo'
  defaults:
    _controller: 'Drupal\custom_service\Controller\CustomserviceController::demo'
    _title: 'My custom service demo'
  requirements:
    _permission: 'access content'

custom_service/src/Controller/CustomserviceController.php:

<?php
namespace Drupal\custom_service\Controller;
use Drupal\Core\Controller\ControllerBase;

class CustomserviceController extends ControllerBase{
	
	public function demo() {		
		return ['#markup' => \Drupal::service('custom_service.demo')->toUpperCase('Some string in uppercase')];
	}
}

In the render array in demo() above our service or more precisely its method toUpperCase() gets called.

We don't need a .module file in this case but we do need custom_service.services.yml right in our module's root folder. There's not a lot to go in there but these three lines are mandatory for our service to work:

services:
  custom_service.demo:
    class: Drupal\custom_service\DemoService

The second line declares the machine name of the service.
The third line denotes its class.

What remains is the service class itself (Drupal\custom_service\DemoService) that gets defined in custom_service/src/DemoService.php:

<?php
/**
 * @file
 * Contains Drupal\custom_service\DemoService.
 */
namespace Drupal\custom_service;

class DemoService {  
  public function toUpperCase($str) {
    return strtoupper($str);
  }  
}

Navigate to website.com/custom_service-demo to see the service in action.
Download the source code from GitHub