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

Published

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?

Source: Laravel

Published
Categorised as design-patterns, laravel, php Tagged , ,

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq