目标 [App\Interfaces\IPostRepository] 在构建时不可实例化

Target [App\Interfaces\IPostRepository] is not instantiable while building

我正在尝试在 laravel 中执行存储库模式,我有很多模型,所以我按以下方式绑定它们

public function register()
{
    $intPath = "App\Interfaces\";
    // models come from models() method
    foreach ($this->models() as $model) {
        $interface = $intPath."I" . $model . "Repository::class";
        $repoPath = "App\Repositories\".$model."\";
        $this->app->singleton($interface, function ($app) use ($model,$repoPath) {
            $cacheName = $repoPath.$model . "CacheRepository";
            $eloquentName = $repoPath.$model . "EloquentRepository";
            return new $cacheName(new $eloquentName);
        });
    }
}

我检查了接口和存储库路径,似乎是正确的。但仍然给我那个错误

public function __construct(IPostRepository $repository)
{
    $this->post = $repository;
}

我该如何解决这个问题?

我不知道是什么让你使用 singleton。如果我在你那里,我会这样走:

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    $repositoryFileNames = [
        // Write your RepositoryName here in quotes
    ];

    foreach ($repositoryFileNames as $key => $fileName) {

        // Contracts are interfaces only 
        $this->app->bind(
            "App\Repositories\Contracts\{$fileName}Contract",
            "App\Repositories\Classes\{$fileName}"
        );
    }

}

注意 foreach 循环中的文件路径。你只用了 1 个反斜杠,而我用了 2.. 你需要使用相同的.. 2 反斜杠,它应该可以解决你的错误。

另请注意,我没有使用singleton方法。相反,我使用了绑定方法..