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

评论 (写第一个评论)