vendredi 14 janvier 2022

Why is interface used as a type in the Laravel Repository Pattern?

I did a investigation on the Laravel Repository Pattern in order to isolate somehow custom queries and I've also tried it on my internal project.

I'm very satisfied how it works. It's definitely good practice of writing custom queries.

One thing are confusing me about the implementation. This is the way of dependency injection in the controllers.

Here is how the suggested best practice of it looks like:

class UsersController extends Controller
{
    private $userRepository;

    public function __construct(UserRepositoryInterface $userRepository) {
        $this->userRepository = $userRepository;
    }

    public function index() {
        $users = $this->userRepository->all();

        return view('users.index', [
            'users' => $users
        ]);
    }
}

What I don't like here is that parameter type in the constructor. I guess it shouldn't be interface.

In the service provider this interface is connected with only one class (here it is UserRepository) which is implementing that interface and it works with this solution.

I think that it's better solution to use UserRepository here as a type of parameter insted of interface. What do you think about this?

Aucun commentaire:

Enregistrer un commentaire