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>',
    ];
  }
}

评论 (写第一个评论)