Reputation: 2901
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 ?
Upvotes: 1
Views: 610
Reputation: 4020
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..
Upvotes: 2