Drupal 9 理解服务

从D8开始,Drupal就引入了服务的概念,在Drupal中服务可以是任何对象,通过服务容器进行管理。
引入服务是为了解耦和增强可重用性,通过将服务注册到服务容器中,从而实现即插即用。
作为开发人员,最好通过服务容器访问 Drupal 提供的所有服务,以确保系统的解耦特性。

以下是一些常用的内核服务:

使用uuid服务,生成UUID

$uuid = \Drupal::service('uuid')->generate();

使用path.current服务,获取当前路径

$current_path = \Drupal::service('path.current')->getPath();

使用path.alias_manager服务,获取路由的别名

$alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

使用account_switcher服务,切换用户session

  $accountSwitcher = \Drupal::service('account_switcher');
  $account = \Drupal\user\Entity\User::load(USER_ID);
  $accountSwitcher->switchTo($account);

获取所有可用服务

$services = \Drupal::getContainer()->getServiceIds();
dump($services);

你可能感兴趣的:(Drupal 9 理解服务)