Laravel : DESIGN PATTERN REPOSITORY
Tags: larevel, designpatterns, services, repositories
Published: 2024-02-06 11:54:06

🏠 **Short Story:**

I vividly recall my initial encounter with the term "Design Pattern" – a moment of profound confusion as I grappled with whether it was a mere philosophical concept or a collection of abstract theories. The burning question in my mind was: how could such a concept be practically applied to something as tangible as my to-do list project 😅?

As it turns out, design patterns are not elusive philosophies; instead, they are a set of solutions crafted to address recurring problems encountered during the software design process. These solutions present a structured approach to overcome common challenges, equipping developers with established and efficient methods to handle issues that frequently arise during coding.

One of the most renowned examples of a design pattern is the Singleton pattern. Imagine creating a new instance of a MySQL database connection for every single request – not only is it inefficient, but it's also downright impractical. Enter the Singleton pattern, which ensures that only one instance of an object (such as a database connection) is created, streamlining operations and optimizing resource usage.

Certainly! Today, let's delve into one of the essential design patterns within the context of the Laravel framework: the Repository Design Pattern.

**Repository Design Pattern:**

The Repository Design Pattern, a structural pattern, serves to separate the logic responsible for retrieving data from the underlying storage (such as a database) from the rest of the application. In Laravel, this pattern is frequently employed to interact with database models.

In simpler terms, we introduce an intermediary layer between my `UserController` and `UserModel`, which I'll refer to as `UserRepository`. Familiar with CRUD methods, right? Well, let's consolidate them within `UserRepository`.

In my projects, I typically initiate the development process by establishing a dedicated folder named "Repositories" within the "app" directory. The next step is to create a PHP interface; I can name it `RepositoryInterface.php`:

```php
namespace App\Repositories;

use Illuminate\Database\Eloquent\Collection;

interface RepositoryInterface {
    /**
     * create method
     * 
     * @author Topo <topo@test.com>
     * @param  mixed $model
     */
    public function create(array $model);
}
```

This interface serves as a blueprint containing prototypes for essential CRUD (Create, Read, Update, Delete) methods. These methods act as the foundation for implementing the repository design pattern, and for now, we will just use the `create` method.

Next, let's define our `UserRepository` class. To do so, let's create this class and implement the `RepositoryInterface`:

```php
namespace App\Repositories;

use App\Models\User;

class UserRepository implements RepositoryInterface {
    
    public function create(array $user)
    {
        return User::create($user);
    }
}
```

Isn't that easy? Can you see how much your code looks well-separated, readable, and easy to maintain?

The question now is, how can I call this repository in my controller? Well, it's not a big deal. This is where we can use Dependency Injection (DI). In the code below:

```php
namespace App\Http\Controllers;

use App\Repositories\UserRepository;

class UserController extends Controller {
   
//since im using php 8.x im allowed to use this syntax 😅
    public function __construct(protected UserRepository $userRepository)
    {
    }

    public function store(Request $request){
        // Validate your request 
        return $this->userRepository->create($request->all());
    }
}
```
**Conclusion 👋**
In conclusion, the Repository Design Pattern proves to be a powerful and indispensable tool for enhancing the readability of your code and adhering to the Single Responsibility Principle. By adopting this pattern, you can achieve a clean and modular architecture, keeping the logic responsible for data retrieval neatly separated from the rest of your application.

The introduction of the intermediary layer, such as the `UserRepository`, not only streamlines CRUD operations but also contributes to the overall maintainability of your codebase. No longer do you find `User::create()` directly in your controller 🤢, but rather, the creation logic is encapsulated within the dedicated repository. This separation of concerns not only enhances the clarity of your code but also ensures that each component has a specific and well-defined responsibility.

Embracing the Repository Design Pattern is not just about organizing code; it's a strategic move towards creating robust and scalable applications. It empowers developers with a systematic approach to handling data access, making your codebase more maintainable, readable, and aligned with best practices in software design.