在 Laravel 5.x 中使用 Repository Pattern 时,我们应该只在控制器中使用叙述方法吗?

Should we use only narrative methods in controllers when using Repository Pattern in Laravel 5.x?

我在 Laravel 中有一个典型的存储库模式结构。以水果模型为例我有:

Class EloquentFruitRepository 扩展抽象 EloquentRepository 实现 FruitRepositoryInterface.

FruitRepositoryInterface 扩展 RepositoryInterface.

最后 RepositoryInterface 定义了那些通用/共享方法,如 allfindwithcreate

我已经阅读了 Laravel 5 中有关存储库模式的所有内容。我审查了所有 GitHub 个项目并审查了所有关于它的要点,并且...我很担心。

我喜欢只使用叙述方法的方法,如果我的 Fruit 模型应该位于 EloquentFruitRepository

所以在我的控制器中而不是构建像这样的东西:

$fruits = $this->fruitRepository
    ->where('color', '=', 'yellow')
    ->where('is_available', '=', true)
    ->with(['comments'])
    ->orderBy([
        'sweetness' => 'asc'
    ])
    ->all();

只做更好吗

$fruits = $this->fruitRepository
    ->getAvailableYellowFruitsWithPeopleCommentsOrderedBySweetness();

然后在 EloquentFruitRepository 中定义该方法,例如:

public function getAvailableYellowFruitsWithPeopleCommentsOrderedBySweetness(): Collection
{
    $model = $this->makeModel();

    $model
        ->where('color', '=', 'yellow')
        ->where('is_available', '=', true)
        ->with(['comments'])
        ->orderBy([
            'sweetness' => 'asc'
        ]);

    return $model->get() ?? new Collection();
}

所以一般来说,所有这些通用方法应该只在特定的 eloquent 存储库中使用,还是也可以在控制器中使用它们?

目前这两种方式都有效。我问的是最好的 (最好的)实践,不是任何人的偏好。

我们应该只在控制器中使用叙述方法吗?

感谢任何反馈。

您正在寻找 'very best' 实践,但您可能知道,当谈到设计模式时,没有一个通用的 'best practice' 适合所有情况

话虽这么说,一般规则是:当您需要在应用程序的多个位置进行查询时,将其放在存储库中。如果您只需要一次,由您决定

我也会把它放在存储库中,但我会用更短、更易读的名称来命名该方法,即:getAvailableYellowFruits。对我来说,'with' 和 'order by' 部分可以忽略不计,如果你愿意,你可以随时将该信息放在方法

的注释中