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

评论 (写第一个评论)