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. 您期望得到的结果?

Laravel

4. 您实际得到的结果?

没有报错信息

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

已解决,路由没写对,浏览器里/test前面要加个api,因为我在api.php里定义的路由

1年前 评论
讨论数量: 9

protected $testService; public function __construct(testService $testService) { $this->testService = $testService; }

不是这样依赖注入吗 这些不用v吧 $this->app->instance(TestInteface::class,$this->app->make(testTrueProxy::class)); 接口内没写内容

class testTrueProxy extends testProxy implements TestInteface { //注入testService,但testService 没有注册到容器 public function construct(testService $service) { parent::construct($service); } }

1年前 评论
if_have_no_else (楼主) 1年前
cccdz 1年前

TestInteface 這個綁定的不是testTrueProxy類嗎 所以在控制器裡面拿到的testTrueProxy類 因為你在控制器裡面調用testTrueProxy的test方法 但是它沒有這個方法 所以會觸發__call 應該會報函數test未找到的錯誤

1年前 评论
if_have_no_else (楼主) 1年前

file 這個地方不會報錯嗎 你這裡都沒得返回值 但是你定義了返回值要是string

1年前 评论
if_have_no_else (楼主) 1年前
if_have_no_else (楼主) 1年前

已解决,路由没写对,浏览器里/test前面要加个api,因为我在api.php里定义的路由

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!