[英]Target [Interface] is not instantiable while building [Controller]
我正在使用 Laravel 9 並且我有一個這樣的 Controller:
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);
}
}
但現在我得到這個錯誤:
目標 [App\Repositories\HomeRepositoryInterface] 在構建 [App\Http\Controllers\HomeController] 時不可實例化。
那么這里出了什么問題?
我該如何解決這個問題?
好像你沒有介紹服務容器。
為此,最好創建一個如下所示的服務提供者,並將存儲庫 class 引入到容器中。
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,
],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.