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

}

评论 (写第一个评论)