Pet*_*Amo 2 php interface laravel repo laravel-9
我正在使用 Laravel 9,我有一个像这样的控制器:
use App\Repositories\HomeRepositoryInterface;
class HomeController extends Controller
{
private $homeRespository;
public function __construct(HomeRepositoryInterface $homeRepository)
{
$this->homeRespository = $homeRepository;
}
...
Run Code Online (Sandbox Code Playgroud)
这是HomeRepositoryInterface:
<?php
namespace App\Repositories;
interface HomeRepositoryInterface
{
public function newest();
}
Run Code Online (Sandbox Code Playgroud)
这就是它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);
}
}
Run Code Online (Sandbox Code Playgroud)
但现在我得到这个错误:
构建 [App\Http\Controllers\HomeController] 时,目标 [App\Repositories\HomeRepositoryInterface] 不可实例化。
那么这里出了什么问题呢?
我该如何解决这个问题?
小智 7
看来你没有引入服务容器。
为此,最好创建一个如下所示的服务提供者,并将存储库类引入到容器中。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,您应该在 config/app.php 文件中引入该服务提供者。
'providers' => [
...
...
...
App\Providers\RepositoryServiceProvider::class,
],
Run Code Online (Sandbox Code Playgroud)