服务
一、什么是服务?
- 你能够在零碎服务中注册一个对象到容器;
- 服务也是用来bind类的。
二、服务的例子
(一)后期筹备
1. 路由
// 服务测试Route::get('myservice','TestServiceController/index');
2. 控制器
(1)TestServiceController
控制器
应用命令,创立测试服务的控制器:
php think make:controller TestServiceController
(2)TestController
控制器
应用命令,创立绑定到容器的控制器:
php think make:controller TestController
在 TestController
控制器中减少 hello
办法:
<?phpdeclare (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
办法是在所有的零碎服务注册实现之后调用,用于定义启动某个零碎服务之前须要做的操作。
<?phpdeclare (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 控制器
<?phpdeclare (strict_types = 1);namespace app\controller;class TestServiceController{ public function index() { $test = app('test'); $test->hello('Moon'); }}
(四)测试
调用接口,后果如下:
参考资料
- 服务-例子
- 服务-了解
- 文档-服务