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

评论 (写第一个评论)