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()
    ];
  }
 
}

评论 (写第一个评论)