Support the ongoing development of Laravel.io →
posted 10 years ago
IOC

Hi guys, I have question about dependency injection and in this case repositories.

Say I have a UserRepository.

In my construct I inject a User model and a UserValidation class.

public function __construct(User $user, UserValidator $validator)
{
    $this->model = $user;
    $this->validator = $validator;
}

I know the IoC will solve the attributes when I injected the repository in another constructor (say UserController). But how should I handle when I just want a call a quick function on it from another place, say MessageController:

public function messagesForUser($id)
{
    $userRepo = new UserRepository(new User(), new UserValidator());
    return $userRepo->getMessagesForUser($id);
}

Defining the User and UserValidator here again does not seem right, but it is what I have been doing up till now. Is there a better way?

Last updated 2 years ago.
0

Create a ServiceProvider and bind a UserInterface to your repository. You can then $userRepo = App::make('UserInterface'); anywhere.

Last updated 2 years ago.
0

Cool, it works doing it with make! One question, doing App::make() obviously removes the type hinting and my editor can't see my repos functions. And I found I now really miss it since I have a lot of long function names on my repos. Is there any way to type hint or get it working with this approach?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

KarlPi karlpi Joined 20 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.