DEV Community


Discussion on: Laravel Repository Pattern

mnavarrocarter profile image
Matias Navarro Carter

You are right in many things you said. It's true that the repository pattern is used to decouple a specific persistence layer from your domain/application logic.

However, you are not even achieving the benefits you preached about with your interface. The Eloquent jargon in your interface and the type hint to return an Eloquent model are coupling it to Eloquent: you gain nothing of what you aimed for in this case. If you were to eventually replace Eloquent, you'll have a hard time doing so.

This would be a more appropiate, really vendor agnostic approach:

interface UserRepository
    * @return User[]
   public function all(): iterable;

   public function ofId(string $userId): ?User;

   public function add(User $user): void;

   public function remove(User $user): void;

interface User
   public function getId(): string;

   public function getPassword(): string;

   // You get the idea

Your Eloquent models then would have to implement the User interface.

With this approach, you really are abstracting away any possible third party or vendor relationship from your domain.

However, that's going to be hard to do. Active Record is not really the best choice for implementing the repository pattern. It's kinda hard to set up and feels hacky. This is pretty obvious: Active Record ties your models (that belong to your domain layer) to a connection to a relational database, and your model data to a relational table structure. Repository pattern is about doing exactly the opposite.

I recommend you to take a look at Doctrine ORM (but for that you'll have to quit Laravel really) and to read this blog. Also, repositories, models and concepts alike have been around for years. One book that explains them well is Domain Driven Design by Eric Evans. He kinda popularized those concepts, among several others.