系統服務



服務定義

#最簡單的方式就是使用命令列來產生一個服務:

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指令用於產生服務列表,並在系統初始化過程中自動註冊。