ThinkPHP6.0 高速開発マニュアル(ケース編)
/ 系统服务
系统服务
系统服务是指在执行框架的某些组件或者功能的时候需要依赖的一些服务
服务定义
最简单的方式就是使用命令行来生成一个服务:
php think make:service FileSystemService
该服务会自动创建二空方法:register和boot方法。
注册方法
register方法通常用于注册系统服,类似Laravel中的服务提供者, 例如:
<?php namespace app\service; use my\util\FileSystem; class FileSystemService extends Service { public function register() { $this->app->bind('file_system', FileSystem::class); } }
register方法不需要参数
<?php namespace app\service; use my\util\FileSystem; class FileSystemService extends Service { public $bind = [ 'file_system' => FileSystem::class, ]; }
启动方法
boot方法用于定义启动某个系统服务之前需要做的操作。例如:
<?php namespace think\captcha; use think\Route; use think\Service; use think\Validate; class CaptchaService extends Service { public function boot(Route $route, Validate $validate) { $route->get('captcha/[:config]', "\\think\\captcha\\CaptchaController@index"); $validate->extend('captcha', function ($value) { return captcha_check($value); }, ':attribute错误!'); } }
服务注册
在应用的全局公共文件service.php中定义系统服务,系统会自动完成注册以及启动。例如:
return [ '\app\service\ConfigService', '\app\service\CacheService', ];
如果需要在你的扩展中注册系统服务,首先在扩展中增加一个服务类,然后在扩展的composer.json文件中增加如下定义:
"extra": { "think": { "services": [ "think\\captcha\\CaptchaService" ] } },
在安装扩展后会系统会自动执行service:discover指令用于生成服务列表,并在系统初始化过程中自动注册。