关于php:2022829-TP6-服务的基本使用

5次阅读

共计 1106 个字符,预计需要花费 3 分钟才能阅读完成。

服务

一、什么是服务?

  1. 你能够在零碎服务中注册一个对象到容器;
  2. 服务也是用来 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');
    }
}
(四)测试

调用接口,后果如下:

参考资料

  1. 服务 - 例子
  2. 服务 - 了解
  3. 文档 - 服务
正文完
 0