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

评论 (写第一个评论)