创建Services
- .info.yml
.services.yml
123services:service_example.example_service:class: Drupal\service_example\ServiceExampleServicesrc/Service.php
12345678910111213141516171819class 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
class method
1234567891011121314151617181920212223242526272829301.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()];}static method
12$serviceExampleService = \Drupal::service('service_example.example_service');$value = $serviceExampleService->getServiceExampleValue();