11.3 依赖注入和控制器

控制器

龺龶龴龲龯龮龫龧龣龡龟龜龛龘龕龔龒龎龍龉龈龇龃齿龜龴齾 create() 齩齥齢齞龎齚齗齓齑齐齏齋龘齈齄齓齑齂龺龶龴鼿鼼鼹

src/Controller/DIController.php

鼚鼖 ControllerBase

鼚鼖鼎鼊鼇鼄鼀黼黹黸齾齢 ControllerBase 龍龉齐龲龺龶龴黶黵龮龫龧龣齾黳黯齢

  • create() / __construct()
    ControllerBase 黧齐齞龎黤黠黝黛齐龃齿龜龴齾 create() 齩齥齢齞龎默黕龲龯黒黠 create 齩齥龈龇齞龎黐黎齾黋黊龃齿龘黆黂龎黝黛黧 __construct() 齩齥龘麾龔鼊麽麻麷麳麲麯齢return new static() 麦齾黹麤鼀黒黠齩齥麣龈龇黂麡齄鼊齾黤黠麟麞麚齢
  • Route Method
    齞龎齾 conversationAboutMood() 齩齥麈麆麄 —- 黂龲龯齞龎齾龃齿鹽鹼黤黠鹻鹹龘鹵鹴龯黒黠鹻鹹龈龇黤黠鹰鹬鹩鹦齢
<?php
 
/**
 * @file
 * Contains \Drupal\di_example\Controller\DIController.
 */
 
namespace Drupal\di_example\Controller;
 
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\di_example\DITalk;
 
class DIController extends ControllerBase {
 
  /**
   * @var \Drupal\di_example\DITalk
   */
  protected $dITalk;
 
  /**
   * @param \Drupal\di_example\DITalk $DITalk
   */
  public function __construct(DITalk $DITalk) {
    $this->dITalk = $DITalk;
  }
 
  /**
   * When this controller is created, it will get the di_example.talk service
   * and store it.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('di_example.talk')
    );
  }
 
 
  public function conversationAboutMood() {
    // We use the injected service to get the message.
    $message = $this->dITalk->getResponseToMood();
 
    // We return a render array of the message.
    return [
      '#type' => 'markup',
      '#markup' => '<p>' . $this->t($message) . '</p>',
    ];
  }
}

评论 (写第一个评论)