【问题标题】:Laravel: What is the best way to implement a method in a model classLaravel:在模型类中实现方法的最佳方法是什么
【发布时间】:2018-05-24 08:30:14
【问题描述】:

我的Game 模型中有一个简单的搜索方法,我已经实现了如下。

public static function search($season, $week)
{
     $filteredGames = Game::with('season', 'week', 'homeTeam', 'awayTeam')
        ->when($season != null, function ($q) {
            return $q->where('season_id', request('season'));
        })->when($week != null, function ($q) {
            return $q->where('week_id', request('week'));
        })
        ->paginate(15);

       return $filteredGames;
}

并像这样在控制器中使用它

$games = Game::search(request('season'), request('week'));

看起来效果很好。

我想了解在设计模式和 SOLID 原则方面,使用静态方法是否是实现此类功能的最佳方式。

任何帮助将不胜感激。

【问题讨论】:

  • 如果您使用 Eloquent,那么您已经违反了 SOLID 中的大部分原则。静态方法本质上是程序性的(并且是全局范围的)。要在您的代码中实际使用 SOLID 原则,您必须停止使用 Laravel。所以......您可能不应该担心它的最佳实践,而只需专注于完成项目并拿起下一个(我假设您正在使用 Lravle 进行一个小型一次性项目)。
  • 这并没有错。但是如果你使用存储库模式会更好
  • @tereško 我正在使用 Eloquent。我违反了 SOLID 中的哪些原则以及如何违反?谢谢。
  • @Tartar 当然,你去吧:S - 活动记录包含持久性和域逻辑,它有多种改变的原因,O - 如果表结构发生变化,你需要改变类,L -子类不是超类的特殊情况,但具有新的和不相关的行为。 I 和 D - 接口是全局范围的,这使得每次使用它都是一个隐藏的依赖项

标签: php laravel laravel-5 design-patterns solid-principles


【解决方案1】:

感谢 IFR 上面的评论,我将我的实现更改为我认为最适合 Laravel 的方法。

public function scopeOfFilter($query, $season, $week)
{
    return $query->with('season', 'week', 'homeTeam', 'awayTeam')
        ->when($season != null, function ($q) {
            return $q->where('season_id', request('season'));
        })->when($week != null, function ($q) {
            return $q->where('week_id', request('week'));
        })
        ->paginate(10);
}

【讨论】:

    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多