无法在 Laravel 10 中绑定接口

问题描述 投票:0回答:1

虽然我已经绑定了我的处理程序,并在

AppServiceProvider
中定义了抽象类和具体类,并在
config/app.php
config/service.php
中注册,但每当我使用 php artisan 时,我都会收到错误

IResponseHandler is not instantiable while building [App\Presentation\Handler]

令人惊讶的是,当我将代码作为 docker 容器运行并通过 nginx 调用它时,它不会引发任何错误。另外,如果我在

Handler.php
的构造函数中定义具体类,则不会出现错误。

我的应用服务提供商:

use App\Framework\ResponseHandler\IResponseHandler;
use App\Framework\ResponseHandler\ResponseHandler;

class AppServiceProvider extends ServiceProvider
{
    /**      * Register any Application services.      */
    public function register(): void
    {
        $this->app->bind(IResponseHandler::class, ResponseHandler::class);
    }
...
}


我的处理程序.php:

class Handler extends ExceptionHandler
{
    public function __construct(protected IResponseHandler $responseHandler)
    {
        parent::__construct(app());
    }
...
}

IResponseHandler:

namespace App\Framework\ResponseHandler;
interface IResponseHandler
{
    public function success(mixed $data = \[\], mixed $meta = null, int $status = 200);

    public function failed(ExceptionResponse $error, int $status = 400);

}

响应处理程序:

namespace App\Framework\ResponseHandler;
class ResponseHandler implements IResponseHandler
{

    public  function success(mixed $data = [], mixed $meta = null, int $status = 200): JsonResponse
    {
        return response()->json(['success' => true, 'data' => $data,  'meta' => $meta,], status: $status);
    }
    
    public  function failed(ExceptionResponse $error, int $status = 400): JsonResponse
    {
        return response()->json(['success' => false, 'error' => $error], status: $status);
    }

}

我不希望在使用 php artisan 命令时出现任何错误。

php laravel composer-php
1个回答
0
投票

也许导入不正确,您是否尝试使用完整路径:

$this->app->bind('\App\Framework\ResponseHandler\IResponseHandler', '\App\Framework\ResponseHandler\ResponseHandler');

© www.soinside.com 2019 - 2024. All rights reserved.