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

没有报错信息

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案

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

2个月前 评论
讨论数量: 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); } }

2个月前 评论
if_have_no_else (楼主) 2个月前
cccdz 2个月前

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

2个月前 评论
if_have_no_else (楼主) 2个月前

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

2个月前 评论
if_have_no_else (楼主) 2个月前
if_have_no_else (楼主) 2个月前

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

2个月前 评论

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