11.2 依赖注入和服务

注入服务

龶龵龴龰龬龩龧龥龣龠龬龩龝龛龬龩龚龗龖龕龬龩龒龐龍龉龇龃齿齼齹齵齳齰齭齪齨齥龕齢齞齜齛龬龩齿龬龩龗齘齕齔齑齏齎龖齌齊齉齇齅 services.yml 龵鼦鼢龴龰龖齌齊齉鼡齼齳齰鼠鼝鼛鼙鼗龴龰齿 di_example.services.yml 龵鼦龗齪齨齥龕齢齞 current_user di_example.mood_ring 龬龩 齿 di_example.talk 龬龩齼

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

  # A service that will let us talk to users.
  di_example.talk:
    class: Drupal\di_example\DITalk
    # We can inject the current user and mood ring services into this service.
    arguments: ['@current_user', '@di_example.mood_ring']

龖龕龬龩黴黳齥龕 getResponseToMood() 黣黡龗點黚齥龕黖黓黏黎黌齼龖龕龬龩龒黈黇黄齪齨 __construct() 黣黡龗黂齏齎齿龬龩麿麽麻龚麺麸齼麷龖麴麳

public function __construct(AccountProxy $CurrentUser, DIMoodRing $DIMoodRing) {

src/DITalk.php齇麤麣麡麞麜麚鼡

麘 PhpStorm 麓麐麏龚龝龧龗齹齵麎麊麈黈麇麄麃麀 use 鹼鹸齼AccountProxy 麎麊龗鹳麻麈齢齞龠鹯鹮龝黖鹫鹨龗鹧 DIMoodRing 鹯麎麊龗鹳麻麈鹥齢齞鹤齳齰鹠鹞鹮麴齿龝黖鹫鹨齼

龍鹛 __construct() 黣黡鹗龗齞 /** 麃麀齥龕齏鹒齼PhpStorm 黈麇麄黴黳鹏鹎龵鹌龗鹈鹆鹄麈齰齿龍鹁龚鸾鸺齼齹齵鸷龴龰龚麺麸龗鹮麴麃麀齏鹒齿鸴龗PhpStorm 黈黴黳麺麸龚鸳齿龵鹌齼

<?php
/**
 * @file Contains \Drupal\di_example\DITalk
 */
 
namespace Drupal\di_example;
 
use Drupal\Core\Session\AccountProxy;
 
/**
 * A service that provides a system for getting response message.
 */
class DITalk {
  protected $responsesToMood = [
    'Very Sad' => 'I hope you feel better.',
    'Sad' => 'are you ok?',
    'So-so' => 'good morning.',
    'Happy' => 'what\'s Up?',
    'Very Happy' => 'you seem happy today!',
  ];
 
  /**
   * @var \Drupal\di_example\DIMoodRing
   */
  protected $dIMoodRing;
 
  /**
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUser;
 
  /**
   * We will inject our two services and store them for use in our service methods.
   *
   * @param \Drupal\Core\Session\AccountProxy $CurrentUser
   * @param \Drupal\di_example\DIMoodRing $DIMoodRing
   */
  public function __construct(AccountProxy $CurrentUser, DIMoodRing $DIMoodRing) {
    $this->currentUser = $CurrentUser;
    $this->dIMoodRing = $DIMoodRing;
  }
 
  /**
   * Returns a string that is a message to a user.
   *
   * @return string
   */
  public function getResponseToMood() {
    // We can user our services and their defined methods.
    $username = $this->currentUser->getUsername();
    $mood = $this->dIMoodRing->getMood();
 
    // We build a message to return.
    return $username . ', ' . $this->responsesToMood[$mood];
  }
}

评论 (写第一个评论)