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

评论 (写第一个评论)