I have a typical repository pattern structure in Laravel. Taking Fruits model as an example I have:
Class EloquentFruitRepository that extends abstract EloquentRepository that implements FruitRepositoryInterface.
FruitRepositoryInterface extends RepositoryInterface.
Finally RepositoryInterface defines those generic / shared methods like all, find, with, create etc.
I have read literally everything about Repository Pattern in Laravel 5. I reviewed all GitHub projects and reviewed all gists about that and... I have concern.
I like the approach of using just narrative methods, that in case of my Fruit model should sit in EloquentFruitRepository.
So in my controller instead of building the stuff like:
$fruits = $this->fruitRepository
->where('color', '=', 'yellow')
->where('is_available', '=', true)
->with(['comments'])
->orderBy([
'sweetness' => 'asc'
])
->all();
is it better just to do
$fruits = $this->fruitRepository
->getAvailableYellowFruitsWithPeopleCommentsOrderedBySweetness();
and then define that method in EloquentFruitRepository like:
public function getAvailableYellowFruitsWithPeopleCommentsOrderedBySweetness(): Collection
{
$model = $this->makeModel();
$model
->where('color', '=', 'yellow')
->where('is_available', '=', true)
->with(['comments'])
->orderBy([
'sweetness' => 'asc'
]);
return $model->get() ?? new Collection();
}
So in general, should all those generic methods be used only within particular eloquent repositories or is it fine to use them also in controller?
Currently both ways work. I'm asking about best (the very best) practice, not anyone's preference.
Should we only use narrative methods in controllers?
Thanks for any feedback.
Aucun commentaire:
Enregistrer un commentaire