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

评论 (写第一个评论)