Creating a service in .services.ymlfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

As you delve deeper into Drupal module development, understanding how to create and manage services is crucial. Services in Drupal are PHP objects that provide a shared functionality, and they form a core part of Drupal’s architecture. In this lesson, we'll explore how to create a service in the .services.yml file, aiding in flexible, reusable code that adheres to the principles of dependency injection.

What is a Service?

In Drupal, a service is an object that performs operations such as executing database queries, sending emails, generating HTML, or any operation that your module might require. These services are defined in the .services.yml file and make your code cleaner and more organized by separating functionality into discrete units.

Why Use Services?

Services offer numerous benefits, including:

  • Reusability: Write once, use globally within your module.
  • Maintainability: Keep specific functionality isolated and easier to manage.
  • Testability: Isolate functionality for independent testing.

Creating a Service

To create a new service, you need to define it in your module's .services.yml file and implement the service class in PHP.

Step 1: Define the Service in .services.yml

In your custom module directory, create or edit a file named example_module.services.yml. Define your service with the following structure:


    services:
      example_module.custom_service:
        class: Drupal\example_module\CustomService
        arguments: ['@logger.channel.example_module']
    

In this file, we define a service named example_module.custom_service with a class CustomService. We also specify arguments for the service, which in this case is a logger service.

Step 2: Create the Service Class

Write the PHP class that implements the defined service. In your module's src directory, create a file named CustomService.php with this content:


    namespace Drupal\example_module;

    use Psr\Log\LoggerInterface;

    class CustomService {

        protected $logger;

        public function __construct(LoggerInterface $logger) {
            $this->logger = $logger;
        }

        public function logMessage($message) {
            $this->logger->info($message);
        }
    }
    

This class uses dependency injection to include the logger service. The logMessage() method logs messages at the 'info' level.

Using Your Service

To use this service in your module, you can inject it into a form or a controller. Here's an example using a controller:

Example Usage in a Controller

In your module, create a controller file ExampleController.php:


    namespace Drupal\example_module\Controller;

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

    class ExampleController extends ControllerBase {

        protected $customService;

        public function __construct(\Drupal\example_module\CustomService $customService) {
            $this->customService = $customService;
        }

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

        public function logExample() {
            $this->customService->logMessage('This is a test log message.');
            return [
                '#markup' => 'Check the logs for the test message.',
            ];
        }
    }
    

This controller demonstrates how to inject and utilize the custom service within a functional class.

Best Practices

  • Encapsulation: Only expose methods necessary for external use.
  • Simplicity: Keep services focused, performing one task efficiently.
  • Documentation: Clearly document what the service does, its dependencies, and its methods.

Common Challenges

Creating and managing services can yield challenges like:

  • Complexity: Mismanaged services can introduce unnecessary complexity.
  • Dependency Managing: Over-relying on services can make systems rigid; ensure dependencies are well-thought-out.

Conclusion

Services are a powerful tool in your Drupal module development toolkit. They foster clean, maintainable, and reusable code, helping manage complex functionalities efficiently. By understanding how to create and manage services, you enrich your ability to develop modular and extensible Drupal applications.

What’s Next?

Next, we'll explore injecting core or custom services into your service, further enhancing modular design and potentially automating complex workflows by combining multiple services.