8.2 服务和控制器

创建个控制器

龺龸龶龳龯龭龪龦龢龞龚龘龖龕龔龒龑龐龌龉龇龃 simple_example() 齣齢齞齚齘齔齐齏齋齈齇齆齂齀齢鼽龇鼼鼻鼸鼵鼴鼱齆鼮鼭鼫龇鼧鼤鼠龺龸鼞龦龢龞鼼鼻 ControllerBase 鼵龇龺龸鼋鼉鼅齏鼂黿龚黽黻龺龸黷黳黯黫龔龒龇

<?php
 
/**
 * @file
 * Contains \Drupal\service_example\ServiceExampleController.
 */
 
namespace Drupal\service_example\Controller;
 
use Drupal\Core\Controller\ControllerBase;
 
class ServiceExampleController extends ControllerBase {
  /**
   * {@inheritdoc}
   */
  public function __construct() {
  }
 
  /**
   * {@inheritdoc}
   */
  public static function create() {
    return new static(
    );
  }
 
  public function simple_example() {
    return [
      '#markup' => 'Hello World'
    ];
  }
}

向控制器追加服务

黧龪黻龔龒黦黢龚龺龸黻齘點黚黖黕黑黏黋dependency injection麾鼞齇麻麷麴龇龃龺龸鼞麳麲齞龯龭齔龚create() 齣齢齞齚齘龇create() 齣齢麰麯齚 __construct() 齣齢龇龖麳麲齞龯龭麭麯龚simple_example() 齣齢齞齚齘龇Drupal 8 麥龚麤麡齢龦龢龞鼞 create() 齣齢齏麞麛齇齆麙龞麗齢龇麓麒麐麭龚黽齆麙龞點麌麈麅黯黫龔龒龇麃麡鹿鹽龖麭麯鹼鹺麥齏鹹鹵龇create() 齣齢黻齘鹴齆麙龞麗齢鹱鹭龔龒龚鹬龕龔龒鹩鹧鹥 __construct() 齣齢龚麭麯 __construct() 齏龕龔龒鹤鹠黧鼵鹞鹝龇

鹙鹕鹑鹏鹋鹊鹇鼞鹄龚鹴鹃龺龸鹀鸼鸹鸷鸳龚龑龐齇齆龔龒鼞鼸鼧鸲鼫鼱黽鸯鸮

  1. 龖龦龢龞鸪黻齘 create() 齣齢齋齈龔龒龇
  2. 鹩鹧黽齆龔龒黿 __construct() 齣齢龇
  3. 龕龔龒鸧黧鼵鹞鹝鹤鹠鹏鹋龇
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('service_example.example_service')
  );
}

麲龺龸鷷鹵鼞鹴鸯龚create() 齣齢麛齇齆 ContainerInterface 鼵鷶鼞麗齢龇齐麛齇齆鹀鷴鼞齣齢 get()龚龺龸齘齐鹭黿龔龒麳麲龇齋齈 new static() 鼧鷲鷱齚齘 __construct() 齣齢龇龘龖龺龸鷭麛齇齆麗齢龚鷪麌麈麅黻齘鷦鷣鷠鷜鼞麗齢鷚鷖鹩鹧麡齆龔龒龇

public function __construct(ServiceExampleService $serviceExampleService) {
  $this->serviceExampleService = $serviceExampleService;
}

黽齆齣齢龕鹩鹧鷉鹋鼞龔龒鹤鹠黧齇齆鹞鹝龇

/**
* @var \Drupal\service_example\ServiceExampleService
*/
protected $serviceExampleService;

龘龖龺龸龯龭齇齆鸼鼞鹞鹝龇黻齘鶿鶽鼞 class 鼵鷶龚龺龸黻齘 use 鶻鶹鶶龕鶴龸鶰鶮龖鶭鶫鶧鶣龇

龘龖龺龸麈麅龖 simple_example() 齣齢鸪黻齘龔龒鼞 getServiceExampleValue() 鸲鼫龪龇

public function simple_example() {
  return [
    '#markup' => $this->serviceExampleService->getServiceExampleValue()
  ];
}

鶕鶓鼞 ServiceExampleController.php 鶭鶫黋鶑鶍鶉鸪麙鶅麾鸮

龘龖麈麅鶁鵽黽齆麷鵹龚鼂鸳 /examples/service-example/simple 鼞黢鹕龇

<?php
 
/**
 * @file
 * Contains \Drupal\service_example\ServiceExampleController.
 */
 
namespace Drupal\service_example\Controller;
 
use Drupal\service_example\ServiceExampleService;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
 
class ServiceExampleController extends ControllerBase {
 
  /**
   * @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()
    ];
  }
 
}

评论 (写第一个评论)