system service



Service definition

The easiest way is to use the command line to generate a service:

php think make:service  FileSystemService

The service will automatically create two empty methods: register and boot methods.

Register method

The register method is usually used to register system services, similar to the service provider in Laravel, for example:

<?php
namespace app\service;

use my\util\FileSystem;

class FileSystemService extends Service
{
    public function register()
    {
        $this->app->bind('file_system', FileSystem::class);
    }
}

The register method is not required Parameters

<?php
namespace app\service;

use my\util\FileSystem;

class FileSystemService extends Service
{
    public $bind = [
        'file_system'    =>    FileSystem::class,
    ];
}

Startup method

The boot method is used to define the operations that need to be done before starting a system service. For example:

<?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 registration

Define the system service in the application’s global public file service.php, and the system will automatically complete it Register and start. For example:

return [
    '\app\service\ConfigService',
    '\app\service\CacheService',
];

If you need to register a system service in your extension, first add a service class in the extension, and then add the following definition in the extension’s composer.json file:

"extra": {
    "think": {
        "services": [
            "think\captcha\CaptchaService"
        ]
    }
},

In After installing the extension, the system will automatically execute the service:discover command to generate a service list and automatically register it during the system initialization process.