gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:25:04 25 4
gpt4 key购买 nike

在 Laravel 4 中,我有几个接口(interface)当前绑定(bind)到 Eloquent 存储库。在我的 Controller 中,我会这样做:

use Acme\Repositories\User\UserRepository;

class UserController extends BaseController {

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


public function __construct(UserRepository $users)
{
$this->users = $users;
}

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

但是,我如何在自己的类里面做到这一点?

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

class HipChatService implements ServiceInterface {

protected $notifications;

public function __construct(NotificationRepository $notifications)
{
$this->notifications = $notifications;
}

要在 route 进行测试:

use Acme\Services\HipChat\HipChatService;

Route::get('hipchat', function()
{
$h = new HipChatService();
});

然后我收到错误:

传递给 Acme\Services\HipChat\HipChatService::__construct() 的参数 1 必须是 Acme\Repositories\Notification\NotificationRepository 的实例,未给出

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

干杯

最佳答案

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

$myInstance = App::make('Acme\Services\HipChat\HipChatService');

关于php - Laravel - 在自己的类中使用存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25015090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com