11.1 依赖注入回顾

龷龵龱龰龬龨龥龤龡龞龛龚龖 龕龒龏services龀龤齼齸齷龏controllers龀齥齣齠龏plugins龀齕齔齒齑齍龷齉齆齒齑龥龡龞齅齂龖鼿鼼鼺鼷鼶鼲鼮鼫齍龷鼨鼤鼣龥龤龡龞鼢鼟鼞齆鼚鼖龰鼓鼑龤鼏鼌鼉鼿鼼鼺鼷 PhpStorm 黾黻龡龞鼺鼷齉齆齒齑齍

安装基础例子模块

龡龞黺黶黵黴黰黬黫龕龒龤鼞黫齼齸齷齥鼞黫黩黦齣齠龰 di_example 齒黦齍龡龞黛黙黶黵黖黓黐鼶鼲鼮鼫龰黍黉黅黁麽 .info.yml .routing.yml 麴齠龤麳黐鼞黫龕龒齍齉黫龕龒黖鼶鼲麯麭龰龕龒齍

di_example.info.yml

name: Dependency Injection Example
type: module
description: Examples on how to use dependency injection
core: 8.x
package: Examples

di_example.routing.yml

齉黫麴齠龥龤龡龞麪麧鼞黫麥麤麣麢龰齼齸齷龤麞鼢鼟鼞黫麜麙麕麒龤龡龞麐麞麏麎龏conversation龀齍麏麎麊麉鼷麆龰麅麄龏mood 龀齍

di_example.conversation_mood:
  path: '/examples/conversation/mood'
  defaults:
    _controller: '\Drupal\di_example\Controller\DIController::conversationAboutMood'
  requirements:
    _access: 'TRUE'

di_example.services.yml

齉黫龕龒鼷麉鼮鼫龡龞龰麯麭麀齠齍麞鹾鹼鼞黫鹻齕麅麄麥麤鹹鹷鼢鼟鼞黫麅麄齍龡龞麪鼢鼟鼞黫麅麄鹳鹰麳黐鼞黫鼷麉鹬鼤鹻齕麅麄龰 getMood() 鹣鹟齍

services:
  # A service that will let us get a mood.
  di_example.mood_ring:
    class: Drupal\di_example\DIMoodRing

齉黫麴齠鼢鼟黶黵鹝麅龰鹜鹙龏src/DIMoodRing.php龀麽

<?php
/**
 * @file Contains \Drupal\di_example\DIMoodRing
 */

namespace Drupal\di_example;

/**
 * A Service for reading a mood from a mood ring.
 *
 * This service does not have any dependencies.
 */
class DIMoodRing {
  protected $moods = [
    0 => 'Very Sad',
    1 => 'Sad',
    2 => 'So-so',
    3 => 'Happy',
    4 => 'Very Happy',
  ];

  /**
   * Returns a string that tells the user's current mood.
   *
   * @return string
   */
  public function getMood() {
    return $this->moods[rand(0,4)];
  }
}

评论 (写第一个评论)