laravel框架学习服务容器问题
1. 运行环境
window phpstorm里 php artisan serve
1). 当前使用的 Laravel 版本?
9.52.16
//: <> (使用 php artisan --version
命令查看)
2). 当前使用的 php/php-fpm 版本?
PHP 版本:8.1.21
php-fpm 版本:
3). 当前系统
Windows 10
4). 业务环境
开发环境
5). 相关软件版本
2. 问题描述?
关于注册服务,使用服务没有生效,没有输出结果?看meedu开源代码,学习其写法,我简化了内容,调用方式没变
在app/Providers/AppServiceProvider.php内 register()注册服务
$this->app->instance(TestInteface::class,$this->app->make(testTrueProxy::class));
再其boot方法中定义
app ()->instance(testinterface::class,$this->app->make(testService::class));
接口内没写内容
class testTrueProxy extends testProxy implements TestInteface
{
//注入testService,但testService 没有注册到容器
public function __construct(testService $service)
{
parent::__construct($service);
}
}
class testProxy
{
protected $service;
public function __construct($service)
{
$this->service = $service;
}
public function __call($name, $arguments)
{
return $arguments ? call_user_func_array($name, $arguments) : call_user_func($name);
}
}
class testService implements TestInteface
{
public function test(): string
{
echo 'test';
}
}
class TestController extends Controller
{
protected $testService;
public function __construct(TestInteface $testService)
{
$this->testService = $testService;
}
//路由到这个方法 没有打印test
public function index()
{
$this->testService->test();
}
}
3. 您期望得到的结果?
4. 您实际得到的结果?
没有报错信息
已解决,路由没写对,浏览器里/test前面要加个api,因为我在api.php里定义的路由