If you have worked with Laravel long enough, you probably saw the Repository pattern used quite a lot 5-10 years ago. But it's not so popular now. Let me demonstrate.
This lesson will be a bit more opinionated but based on the strong opinions of a few more influential Laravel community members.
In some Laravel tutorials, especially older ones, you may find example similar to this:
namespace App\Http\Controllers; use App\Repositories\UserRepository;use Illuminate\View\View; class UserController extends Controller{ public function __construct( protected UserRepository $users, ) {} public function show(string $id): View { $user = $this->users->find($id); return view('user.profile', ['user' => $user]); }}
Then, the Repository class may look something like this:
app/Repositories/UserRepository.php:
class UserRepository{ public function find($id) { return User::find($id); }}
But this doesn't seem very useful. Why a Repository with $this->users->find()
instead of just User::find()
? A separate class for doing the same thing?
Typically, the authors of those tutorials emphasize mocking or swapping the repository class with some other class in the future, for better testability and isolation.
But this typical over-simplified example above doesn't do the justice to the idea of Repository pattern in general.
Let me show you better examples, and then I will still debate that I do NOT approve of them in Laravel.
To actually show the "swapping" and "mocking" idea from the same example above, it should be...