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

评论 (写第一个评论)