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

评论 (写第一个评论)