How to define your own Services in Drupal 8
Blog

How to define your own Services in Drupal 8

Service  is a PHP class with some code that provides a single specific functionality throughout the application. So you can easily access each service and use its functionality wherever you need it. Because of that it is easy to test and configure in your application. This is called service-oriented architecture which is not unique to Symfony or even PHP.  

The Services and Dependency Injection Container concepts have been adopted by Drupal from the Symfony framework.  Accessing the database, sending email, or translating user interface are examples for the services in Drupal 8. 

Lets look at how to define your own service in drupal 8 custom module Development?

 

Step 1:
Create the .info.yml file [custom_services_example.info.yml]

Step 2:
Create the ‘mymodulename.services.yml’ file [custom_services_example.services.yml]

Here the file name is ‘custom_services_example.services.yml’ where the ‘custom_services_example’ is our module name.

custom_services_example.say_hello’ is the service name defined by us, , Where we need to follow the pattern of ‘module_name’ concatenate with a ‘unique_name’.

We have the class name for services. ‘class: Drupal\custom_services_example\HelloServices’ which will be kept under the ‘src’ folder.

Also the dependency can be added the  following way 
arguments: ['@modulename.services1', '@modulename.services4', '@modulename.services7']  
In this case there are no  dependencies.

For the detailed explanation on  the structure of the .services.yml file please visit https://www.drupal.org/node/2194463

Step 3:
Create the class ‘HelloServices.php’ under the ‘src’ folder

This is simple class provide the service.

How to access the our own defined service?

Accessing the service globally. 

$service = \Drupal::service('custom_services_example.say_hello');

If you want to test this , you can enable the devel module and go to the path ‘devel/php’ and  run the following code 

 

$service = \Drupal::service('custom_services_example.say_hello');
dsm($service);
dsm($service->sayHello('rakesh'));

So you will get the following output.

 

  • Drupal\custom_services_example\HelloServices Object
    (   
          [say_something:protected] => Hello World!   
          [_serviceId] => custom_services_example.say_hello
    )
     
  • Hello rakesh!
     


https://github.com/rakeshjames/custom_services_example

For  more details please visit  the following links

  1. https://www.drupal.org/node/2133171
  2. http://symfony.com/doc/current/book/service_container.html