【问题标题】:How to use an Interface Repository in a Laravel Nova Action?如何在 Laravel Nova Action 中使用接口存储库?
【发布时间】:2020-11-09 16:26:59
【问题描述】:

我正在使用Laravel Repository Pattern 来管理我的资源,我想知道如何在 Nova Action 中使用界面?由于无法实例化接口,我想知道如何在我的操作中使用我的接口?

在我的 Controller 构造函数中,我创建了我的存储库,然后我可以在我的函数中使用它,但是我不知道如何在 Laravel Action 中做同样的事情。

知道我该怎么做吗?

我的控制器中的一个例子

private $myRepository;

public function __construct(
    MyRepositoryInterface $myRepository,
)
{
    $this->myRepository = $myRepository;
}

然后在函数内部我可以做类似的事情

public function destroy($id)
{
    $this->myRepository->delete($id);

    return response()->json( array("message" => "success") );
}

现在在我的 Nova Action 中,这就是我想要做的事情

public function handle(ActionFields $fields, Collection $models)
{
    foreach ($models as $model)
    {
        $myRepository = new MyRepositoryInterface(); // This doesn't work obviously
        $myRepository->customManipulation($model->id);
        $this->markAsFinished($model);
    }
}

知道如何使用我的存储库吗?

谢谢!

【问题讨论】:

  • MyRepository 是否实现了MyRepositoryInterface 接口?你说new MyRepository() 不起作用,但这只是一个构造函数,所以如果MyRepository 是一个类而不是throw,它不应该失败。

标签: php laravel laravel-nova


【解决方案1】:

你可以$myRepository = App::make(MyRepositoryInterface::class);,IoC 会解决它并实例化一个类实例。

我假设您已经将类绑定到接口:

App::bind('MyRepositoryInterface', 'MyRepository');

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2014-09-13
    • 2021-11-16
    • 2014-03-12
    相关资源
    最近更新 更多