How to use Repositories in Laravel Framework, not to repeat code

How to use Repositories in Laravel Framework, not to repeat code

One of the big problems in software development is code repetition, this adds a lot of difficulty when maintaining the project.

So there is a concept in software development called DRY (The Don't Repeat Yourself), this concept proposes that you don't repeat your code, if you need to do the same action, in more than one place in your project, you must create an abstraction for that.

To apply the DRY concept in Laravel framework there are some architectures developed by the community, today we are going to talk only about Repositories.

Imagine the scenario, you have a system where the user can be registered alone to have access to a logged in area, but someone who is already registered in the system, can also invite that same user through an invitation.

It is not difficult to see that you will need two codes to register a user, one outside the application and one inside.

Well to solve this type of situation we will use a Repository called "UserRepository.php"

UserRepository.php

UserRepository.php is an abstraction that we can call wherever we want.

In our example we will have two controllers, the RegisterController.php (for external registrations) and UsersControllers.php (for internal registrations).

As you can see I can call UserRepository.php from both Controllers and I'm not repeating myself.

RegisterController.php

I can also make the same call from UsersController.php

UsersController.php

That way you can make maintaining your software much simpler and more effective.

Because when you need to fix a bug or implement a new feature, you know that you will only need to edit UserRepository.php

Repositories also serve to facilitate cache reprocessing, imagine that you redo the user's cache using several different methods of your application, with repositories you will always call the same method.

Did you already know the Laravel repositories?

If you have any questions, please leave them in the comments below.