Laravel - 在自己的类中使用存储库

Ali*_*ias 2 php repository-pattern laravel

在 Laravel 4 中,我有几个接口当前绑定到 Eloquent 存储库。在我的控制器中,我会这样做:

use Acme\Repositories\User\UserRepository;

class UserController extends BaseController {

    /**
     * @var UserRepository
     */
    protected $users;


    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
Run Code Online (Sandbox Code Playgroud)

然后我可以访问我的自定义方法以使用 Eloquent 获取数据。

但是,我如何在自己的课堂上做到这一点?

use Acme\Repositories\Notification\NotificationRepository;
use Acme\Services\ServiceInterface;

class HipChatService implements ServiceInterface {

    protected $notifications;

    public function __construct(NotificationRepository $notifications)
    {
        $this->notifications = $notifications;
    }
Run Code Online (Sandbox Code Playgroud)

要在路线中进行测试:

use Acme\Services\HipChat\HipChatService;

Route::get('hipchat', function()
{
    $h = new HipChatService();
});
Run Code Online (Sandbox Code Playgroud)

然后我得到错误:

Argument 1 passed to Acme\Services\HipChat\HipChatService::__construct() must be an instance of Acme\Repositories\Notification\NotificationRepository, none given

现在我明白为什么会发生这种情况,但是我应该如何在我自己的类中使用存储库?我怎样才能调用控制器+方法而不发生这种情况?

干杯

小智 5

如果你希望 Laravel 解决你的依赖关系,你必须App::make使用 new 来构建你的对象,而不是手动实例化。

$myInstance = App::make('Acme\Services\HipChat\HipChatService');
Run Code Online (Sandbox Code Playgroud)