我正在使用Laravel 9,我有一个这样的控制器:

use App\Repositories\HomeRepositoryInterface;

class HomeController extends Controller
{
    private $homeRespository;

    public function __construct(HomeRepositoryInterface $homeRepository)
    {
        $this->homeRespository = $homeRepository;
    }

    ...

以下是前HomeRepositoryInterface名:

<?php
namespace App\Repositories;

interface HomeRepositoryInterface
{
    public function newest();
}

这就是HomeRepository强本身:

<?php
namespace App\Repositories;

use App\Models\Question;

class HomeRepository implements HomeRepositoryInterface
{
    public function newest()
    {
        return $ques = Question::orderBy('created_at', 'DESC')->paginate(10);
    }
}

但现在我得到了这样的错误:

Target [App\Repositories\HomeRepositoryInterface] is not instantiable while building [App\Http\Controllers\HomeController].

那么,这里出了什么问题呢?

我怎么才能解决这个问题呢?

推荐答案

您似乎没有介绍服务容器.

为此,最好创建如下所示的服务提供者,并将存储库类引入容器.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Repositories\HomeRepositoryInterface;
use App\Repositories\HomeRepository;

class RepositoryServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        // Bind Interface and Repository class together
        $this->app->bind(HomeRepositoryInterface::class, HomeRepository::class);
    }
}

接下来,您应该在config/app.php文件中引入这个服务提供者.

'providers' => [
    ...
    ...
    ...
    App\Providers\RepositoryServiceProvider::class,
],

Php相关问答推荐

当我们使用PHPUnit时,控制台中的--uses param到底起了什么作用以及如何使用?

在AJX请求中使用简写后,FormData出现非法调用错误

Laravel 10查询中的多个where子句

SQLSTATE [42S02]:找不到基表或视图:1146 Table eshop. sessions不存在'''

使用随机生成器在MYSQL中创建唯一ID-定义一个数组来存储已知ID是否安全

Azure应用程序无法访问共享文件夹

Regex|PHP捕获json字符串中的每个非法双引号

如何批量处理消息总线中的消息

如何在 apache Laragon - laravel 10 中允许方法 DELETE?

用户注册表单中的 HTTP 错误 405

如何使用 PHP 将带有图像的文本上传到 Linkedin?

laravel Eloquent 模型的问题

将 WooCommerce 0 销售价格替换为自定义文本,并保留常规价格删除线

Shopware 6.4.20店铺激活问题

在 Laravel、Vuejs 和 Inertia 中配置 TypeScript 的问题

如果有很多重定向,PHP curl 的行为不像命令行 curl

如何在不解压缩/重新压缩的情况下连接(连接)两个缩小的值

password_verify 在 PHP 7.4 中有效,但在 PHP 8.2 中无效

Eloquent 的模型更新了它应该 laravel php 的更多行

如何在 Laravel 9 中判断异常是否可报告?