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

}

评论 (写第一个评论)