In Drupal 8 service is any object managed by the services container.
services are used to perform operations like accessing the database or sending an e-mail.
like below:
$connection = \Drupal::database();
$result = $connection->select('node', 'n')
->fields('n', array('nid'))
->execute()
you can create your own services, like create common used function with in the class and use it any where, It works like global functions.
To create our own services, just create a services file like modulename.services.yml ,
services:
drupalup_service.cow:
class: Drupal\drupalup_service\CowService
arguments: ['@current_user']
and create the callable class with functions which you like,
lets suppose we create a function
public function whoIsYourOwner() {
return $this->currentUser->getDisplayName();
}
and use in anywhere like
$aa = \Drupal::service('drupalup_service.cow');
kint($aa->whoIsYourOwner());
There are two methods to call the services,
1- Service location ( like \Drupal::database();) 2 - Dependency injection , (to inject as a dependency when create a service)
//Get a service from outside the current class:
$services = \Drupal::service('service_name');
//Equivalant , if you have a $container variable (also known as service container)
$service = $container->get('service_name');
How to call services within non service class with dependencies :
It's achieved by create function in class, the create function( public function create($container){}) with in drupal
fires automatically, it needs one argument $container from container interface,
get github code:
https://github.com/Dharmend/drupalup_service
Comments
Post a Comment