8.1 服务

本课内容

  • 龶龵龴龳 examples/service_example龐龏龋龇龆龄龁齾齼service 齹齸齴齰齭齬齼dependency injection齹
  • 齞齝龁齾齜齘齕齒齴齰齭齬齑齏齌
  • 齉齈齴齰齭齬齑齆龄齜龏龋
  • 齉齈龁齾齅齁齑齆龄齜龏龋
  • 齀齭鼾龁齾鼻鼸鼶鼴鼳鼱鼰鼬鼫鼨鼥鼬鼫齘齕鼡鼟鼜龋鼛
  • 齉齈龶龵齸齭鼙鼖鼓鼏鼌齑龁齾

鼈齕鼄龶龵鼖鼓龆龄 service_example.example_service 龁齾齑龴龳龐黽黻鼻黺黹 examples/service-example/simple 鼴龏龋黳龐黺黹黱鼖鼓鼏鼌齑 ServiceExampleController 黨黦齁黨黦黣

创建基础模块

鼈齕鼄龶龵黡黟點黛黣黽黚黗鼶黖黕黔黒黑黍黊龶龵黈黱齸 info 點黛黣

service_example.info.yml 點黛齼黁麽麹1齹麴

service_example.routing.yml 點黛齼黁麽麹2齹麴

代码1:

name: 'Service example'
type: module
description: 'An example module showing how to create and use a service.'
package: 'Acquia Example modules'
core: 8.x

代码2:

service_example_simple:
  path: 'examples/service-example/simple'
  defaults:
    _controller: '\Drupal\service_example\Controller\ServiceExampleController::simple_example'
  requirements:
    _access: 'TRUE'

创建一个服务

鼈齕鼄龶龵鼖鼓鼏鼌龁齾龐黳麬麫鼖鼓麩麦麣麟麛麗齑麕麒黣

黽黻黗鼶黖鼈齕鼄齞齝麑麏龁齾麍齏麉麈龐麅麂鹿鹼黡鹹黳鹵鹱鼥鹭鹩鹧鹣鹡鹠鹝黣

鹚龶龵鼖鼓龁齾龐鹿鹖鹚龏龋 service_example.services.yml 點黛鹒齌鹎麉鹍黳齑鹊鼻黣黽黻鼻 src/ServiceExampleService.php 點黛鹆鹅鹂鹀龆龄麕麒黣

service_example.services.yml 點黛黖龐鸿鸼鸹鼖鼓龁齾鸵鸲黣鸰鼓龁齾龋龴龳鸯鸮鼥黚鸪 module_name.service_name 黣龁齾齑鹀鸯鸦鸤龆龄龐鹀鸯齸鸡齆鸞鼓鹀齑點黛鸛鸯黣

service_example.services.yml 點黛 麴

services:
  service_example.example_service:
    class: Drupal\service_example\ServiceExampleService

ServiceExampleService.php 點黛鸎鸌鸉鸅鹀鸃黨黦齁齼黁鷿鷾鹆齅鷼齹黣鼈齕鷹鷶龆龄鼬鼫鷳齑鹀龐龆龄鸯麟鷲鷯齼Drupal\module_name齹龐鼈齕龶龵鼖鼓鷮鷫鹧鹣齸鼖鷪鹆鷩鷥鷤黣鸞鼓龁齾齑鹆鷩鷥鷤鸹麴鷠龁齾鸤龶龵麂龐鼖鼓鷞鷝鸤鷙鷗鼥 Student 黣鷠鷔齘麽麹龏龋鸞鼓龁齾麂龐齘齕麒鷑鷍鷋鷊龋 getServiceExampleValue() 鹧鹣麦麣麟麛麗 Student 黣

<?php

/**
 * @file
 * Contains \Drupal\service_example\ServiceExampleService.
 */

namespace Drupal\service_example;

class ServiceExampleService {

  protected $service_example_value;

  /**
   * When the service is created, set a value for the example variable.
   */
  public function __construct() {
    $this->service_example_value = 'Student';
  }

  /**
   * Return the value of the example variable.
   */
  public function getServiceExampleValue() {
    return $this->service_example_value;
  }

}

评论 (写第一个评论)