Creating a custom service

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

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.


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


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 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:

    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:

 * @file
 * Contains Drupal\custom_service\DemoService.
namespace Drupal\custom_service;

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

Navigate to to see the service in action.
Download the source code from GitHub