Drupal service system ========================== :Published at: February 24, 2020 :Author: Erlend ter Maat :Tags: Drupal, Drupal service container ---- Drupal did not give developers a good reason to work OO when developing custom modules or themes... Until Drupal 8! A feature that I've been exploring recently is the services system. What do services look like? --------------------------- Service initialization ^^^^^^^^^^^^^^^^^^^^^^ At a minimum a service is made known to the system like this:: # custom_module.services.yml services: custom_service: class: Drupal\custom_module\Services\CustomService Service body ^^^^^^^^^^^^ A simple example of a service that adds the number two to an unknown parameter value. .. code-block:: php serviceInstance = $serviceInstance; } public static function create(ContainerInterface $container) { return new static( $container->get('custom_service') ); } public function buildForm(array $form, FormStateInterface $form_state) { // Build the form. // ... // Use the service. $maybeTen = $this->serviceInstance->addTwo(8); } } As a dependency at a plugin ^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: php serviceInstance = $serviceInstance; } public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('custom_service') ); } protected function maybeTen() { // Use the service. return $this->serviceInstance->addTwo(8); } } Anywhere else ^^^^^^^^^^^^^ Use the service at any other place where the dependency system is not available for some reason. .. code-block:: php serviceInstance->addTwo(8); } So... ----- Services offer a great way to expose the functionality of your custom module in a structured way to other modules. You can regard it as interfaces to the functionality your module has to offer. The services you create can be used by your own module or by other modules. Applications ^^^^^^^^^^^^ Services can be used for: - REST API's. - Interfaces to your custom entities. - Interface to any kind of processing only your module knows about. - Some Drupal hooks moved to the services system. - Etc. Next time... ------------ With the event_subscriber tag Drupal services offer an object oriented mechanism for hooks:: # custom_module.services.yml services: custom_module.route_subscriber class: Drupal\custom_module\Routing\CustomRouteSubscriber tags: - { name: 'event_subscriber' } So next blog posts I will dive deeper into `the services based new hook system `_.