服务
一、什么是服务?
- 你可以在系统服务中注册一个对象到容器;
- 服务也是用来bind类的。
二、服务的例子
(一)前期准备
1. 路由
// 服务测试
Route::get('myservice','TestServiceController/index');2. 控制器
(1)TestServiceController 控制器
使用命令,创建测试服务的控制器:
php think make:controller TestServiceController(2)TestController 控制器
使用命令,创建绑定到容器的控制器:
php think make:controller TestController在 TestController 控制器中增加 hello 方法:
<?php
declare (strict_types = 1);
namespace app\controller;
class TestController
{
    public function hello($username){
        echo 'hello '.$username."!<br/>";
    }
}(二)TestService 服务类
使用命令创建 TestService 服务类:
php think make:service TestService在 TestService 类的 register 方法中,将 TestController 控制器和 User 模型绑定到容器中。
boot 方法是在所有的系统服务注册完成之后调用,用于定义启动某个系统服务之前需要做的操作。
<?php
declare (strict_types = 1);
namespace app\service;
class TestService extends \think\Service
{
    /**
     * 注册服务
     *
     * @return mixed
     */
    public function register()
    {
        $this->app->bind('test',\app\controller\TestController::class);
    }
    /**
     * 执行服务
     *
     * @return mixed
     */
    public function boot()
    {
        echo '启动本服务前需要完成的操作'."<br/>";
    }
}(三)修改 TestServiceController 控制器
<?php
declare (strict_types = 1);
namespace app\controller;
class TestServiceController
{
    public function index()
    {
        $test = app('test');
        $test->hello('Moon');
    }
}(四)测试
调用接口,结果如下:
参考资料
- 服务-例子
- 服务-理解
- 文档-服务
相关文章
暂无评论...
 
                             
                         
                            