Using the repository pattern is a common solution in modern web applications. Let’s take a quick look at how to write a repository based on Laravel’s collection class.
What are repositories?
So, briefly, repositories are a store where we can perform CRUD actions on its items. We can add a new item to the repository or remove one, update or just simply read them.
Since the items of the repository not necessary need to be stored in a database, they can be simple objects or other values as well, it turns out Laravel’s collection class is a very neat choice to build a repository on. With some custom methods, we are able to extend our repository and customize the class how we need, yet we have the flexibility of the collection implementation. Let’s take a look.
A Very Simple Implementation of a Repository
The collection class is very generic. It means to make our repository “perfect” we need to implement some of our own methods but also, to create the ability to dynamically use the functionality of the collection instance. Let’s see how:
class Repository { /** * The repository items. * * @var \Illuminate\Support\Collection */ protected $items; /** * Create a new repository instance. * * @param array $items * @return void */ public function __construct(array $items = []) { $this->items = collect($items); } /** * Find the item in the repository by the given ID. * * @param string $id * @return mixed */ public function find(string $id) { return $this->items->first(function ($item) use ($id) { return $item->id === $id; }); } /** * Dynamically call a method. * * @param string $name * @param mixed $arguments * @return mixed */ public function __call($name, $arguments) { return $this->items->{$name}(...$arguments); } }
So what is going here? Basically we are using the Repository class is a wrapper around the collection instance. This way we can easily extend its functionality, like the find() method, while the rest of the method calls we pass through the __call magic function that will call the proper method of the collection instance.
It’s a very simple representation of the repository pattern, but yet this can be a big help in certain cases when developing some storage functionality.