understand drupal 8 service

Ng
2019.06.19
Comment

Service: A class instance that is easily accessible and reusable by the system.

可以理解为全局静态变量,随时拿过来用。(仅做理解)

d8 中常见的一种使用情形:

\Drupal::service(‘service.name’);

一个简单实例:

my_module\my_module.services.yml

services: my.custom.service: class: \Drupal\my_module\MyService

my_module\src\MyService.php

<?php namespace Drupal\my_module;

class MyService{ public function doSometing(){ return "hello world!"; } }

my_module\my_module.module

function my_module_help(){ $myService = \Drupal::service('my.custom.service'); $myService->doSomething(); }

drupal
service

Add new comment