Laravel - Using repository in own class
-
21-12-2019 - |
سؤال
In Laravel 4, I have several interfaces which are currently bound to Eloquent repositories. In my controllers, I'd do:
use Acme\Repositories\User\UserRepository;
class UserController extends BaseController {
/**
* @var UserRepository
*/
protected $users;
public function __construct(UserRepository $users)
{
$this->users = $users;
}
I can then access my custom methods to grab data using Eloquent.
However, how do I do this in my own classes?
use Acme\Repositories\Notification\NotificationRepository;
use Acme\Services\ServiceInterface;
class HipChatService implements ServiceInterface {
protected $notifications;
public function __construct(NotificationRepository $notifications)
{
$this->notifications = $notifications;
}
To test in a route:
use Acme\Services\HipChat\HipChatService;
Route::get('hipchat', function()
{
$h = new HipChatService();
});
I then get the error:
Argument 1 passed to Acme\Services\HipChat\HipChatService::__construct() must be an instance of Acme\Repositories\Notification\NotificationRepository, none given
Now I understand why this happens, but how am I supposed to use the repository within my own class? How am I able to call a controller + method without this happening?
Cheers
المحلول
If you want Laravel to solve your dependencies, you must build your object with App::make
instead of instanciate manually with new.
$myInstance = App::make('Acme\Services\HipChat\HipChatService');