What
A service is an object that gets instantiated by a Service Container and is used to handle operations in a reusable way, for example, performing calculations and interacting with the database, an external API, or any number of things. Moreover, it can take dependencies (other services) and use them to help out. Services are a core part of the dependency injection (DI) principle that is commonly used in modern PHP applications and in Drupal 8.
说白了就是MVC的Service层,处理业务逻辑。
How
- 定义自己的Services
在src目录下建立class(如同写Controller类似)
e.g.
namespace Drupal\hello_world;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class HelloWorldSalutation {
use StringTranslationTrait;
public function getSalutation() {
$time = new \DateTime();
if ((int) $time->format('G') >= 06 && (int) $time->format('G') < 12) {
return $this->t('Good morning world');
}
if ((int) $time->format('G') >= 12 && (int) $time->format('G') < 18) {
return $this->t('Good afternoon world');
}
if ((int) $time->format('G') >= 18) {
return $this->t('Good evening world');
}
}
}
- 在自定义module中建立*.services.yml文件
services:
hello_world.salutation:
class: Drupal\hello_world\HelloWorldSalutation
意思是起一个key: "hello_world.salutation"。将来要通过这个key找到对应的class: Drupal\hello_world\HelloWorldSalutation。
- 使用。
使用分为两种方式,一种是动态加载,在需要的时候引进来。另一种则是在构造函数和create方法里面将service注入。
- statically
$service = \Drupal::service('hello_world.salutation')
- injected
/**
* @var \Drupal\hello_world\HelloWorldSalutation
*/
protected $salutation;
/**
* HelloWorldController constructor.
*
* @param \Drupal\hello_world\HelloWorldSalutation $salutation
*/
public function __construct(HelloWorldSalutation $salutation) {
$this->salutation = $salutation;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('hello_world.salutation')
);
}
Tips:
引入Services,引入容器接口
use Drupal\hello_world\HelloWorldSalutation;
use Symfony\Component\DependencyInjection\ContainerInterface;