DEV Community

Discussion on: Repository Pattern in Laravel

Collapse
 
bdelespierre profile image
Benjamin Delespierre

Thanks for this article @davidrjenni , very informative and well-written.

One thing I believe is missing is the whole point of having repositories; to abstract entity management from storage layer. One is able to substitute the storage layer at will. This is immensely helpful when you sync data accross several API, here's an example:

<?php

interface OrderEntity
{
    public function getUuid(): ?string;

    public function getAmount(): int;
}

class Order extends Model implements OrderEntity
{
    // ...
}

interface OrderRepository
{
    public function has(OrderEntity $order): bool;

    public function find(string $uuid): OrderEntity;

    public function save(OrderEntity $order): void;
}

class OrderDatabaseRepository implements OrderRepository
{
    // Saves the order on the database using Eloquent
}

class OrderStripeRepository implements OrderRepository
{
    // Sends the order to Stipe using its API
}

class OrderHubspotRepository implements OrderRepository
{
    // Stores a copy of the order on Hubspot for the sales dept
}
Enter fullscreen mode Exit fullscreen mode

Moving data around becomes as easy as:

$stripeRepository->save($databaseRepository->find($uid));
Enter fullscreen mode Exit fullscreen mode

If the API you're talking to is REST compliant, implementing a repository that talks to it is a breeze (no state to manage.)

There are many other reasons why you would want to use repositories with Laravel. Especially if you're designing with DDD. You can read more about that on my dev.to page 😉

Collapse
 
davidrjenni profile image
David

Thank you, @bdelespierre for your feedback, much appreciated 🙏.

One thing I believe is missing is the whole point of having repositories; to abstract entity management from storage layer.

I'll expand on the reasons I think the Repository pattern is helpful in the next blog post. I wanted to keep this post focused on the general concept and how to implement it in Laravel.

You can read more about that on my dev.to page 😉

I'll definitively check them out 👍. Thanks for the pointer.