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)];
  }
}

评论 (写第一个评论)