Services, dependency injection, and service containers

创建Services

  1. .info.yml
  2. .services.yml

    1
    2
    3
    services:
    service_example.example_service:
    class: Drupal\service_example\ServiceExampleService
  3. src/Service.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class ServiceExampleService {
    protected $service_example_value;
    /**
    * When the service is created, set a value for the example variable.
    */
    public function __construct() {
    $this->service_example_value = 'Student';
    }
    /**
    * Return the value of the example variable.
    */
    public function getServiceExampleValue() {
    return $this->service_example_value;
    }
    }

使用services

  1. class method

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    1.1 Retrieve the service using the Container in the create() function.
    1.2 Pass the service to the __construct() function.
    1.3 Store the service as a class variable.
    /**
    * @var \Drupal\service_example\ServiceExampleService
    */
    protected $serviceExampleService;
    /**
    * {@inheritdoc}
    */
    public function __construct(ServiceExampleService $serviceExampleService) {
    $this->serviceExampleService = $serviceExampleService;
    }
    /**
    * {@inheritdoc}
    */
    public static function create(ContainerInterface $container) {
    return new static(
    $container->get('service_example.example_service')
    );
    }
    public function simple_example() {
    return [
    '#markup' => $this->serviceExampleService->getServiceExampleValue()
    ];
    }
  2. static method

    1
    2
    $serviceExampleService = \Drupal::service('service_example.example_service');
    $value = $serviceExampleService->getServiceExampleValue();

参考资料

Services, dependency injection, and service containers