意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

2022/8/29 TP6 服务的基本使用

来源:恒创科技 编辑:恒创科技编辑部
2024-01-09 01:59:59
服务一、什么是服务?你可以在系统服务中注册一个对象到容器;服务也是用来bind类的。二、服务的例子(一)前期准备1. 路由
// 服务测试
Route::get('myservice','TestServiceController/index');
2. 控制器

(1)TestServiceController 控制器
使用命令,创建测试服务的控制器:

php think make:controller TestServiceController

(2)TestController 控制器
使用命令,创建绑定到容器的控制器:

php think make:controller TestController

TestController 控制器中增加 hello 方法:


2022/8/29 TP6 服务的基本使用

<?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');
    }
}
(四)测试

调用接口,结果如下:
测试服务1.png

参考资料服务-例子服务-理解文档-服务
上一篇: Day 90/100 前端如何启动PHP后端项目 下一篇: 2022/8/29 TP6 模型之多对多