简体   繁体   中英

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

I'm trying to do repository pattern in laravel, I have many models so I'm binding them like below way

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);
        });
    }
}

I check interface and repository path, it seems correct. But still gives me that error

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

How do I fix this ?

I don't know what made you use singleton . If I were at your place, I would have gone something like this:

/**
 * 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}"
        );
    }

}

Notice the file path inside foreach loop. You have used only 1 back slash, while I have used 2.. You need to use the same.. 2 back slash, and it should resolve your error.

Also, note that I have not used singleton method. Instead, I have used the bind method..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM