【问题标题】:Is it bad practice for a model to call itself within itself?模型在自身内部调用自己是不好的做法吗?
【发布时间】:2023-03-09 06:55:02
【问题描述】:

这是一个例子,在 Laravel 中使用 Eloquent。

假设我正在开发 CMS。

  • 控制器获取路由并通过路由查找页面。
  • 模型提供了一个静态函数,该函数使用路由来找出它正在寻找的行的 ID
  • 然后模型使用自己执行数据库查询并返回结果

示例控制器代码:

Route::get('(.*)', function($route)
{
    $page = Page::load_by_route($route);
});

示例型号代码:

class Page extends Eloquent {

    public static function load_by_route($route)
    {
        // Explode the route and trace to find the actual id of the row we need.
        // ... some lines of code to accomplish it...

        // Use the $id we discovered to perform the actual query
        $page = Page::find($id)->first();

        return $page;
    }
}

在你问“为什么你不能首先使用 Page::where('route', '=', $route)->first() 之前:我是不知道“如何做”这个例子。我只是想知道在页面模型中使用 Page:: 是否不好?

【问题讨论】:

  • 为什么不呢?但你可以使用self 代替类名

标签: php laravel eloquent


【解决方案1】:

不,但约定使用self 来引用当前类:

$page = self::find($id)->first();

【讨论】:

  • 我实际上在课堂上使用static::methodName(),但不知道有什么区别
  • @MirkoAkkov 检查 php 5.3+ 中的后期静态绑定以了解 staticself 之间的区别
  • 感谢 Marko D。我刚开始在 Google 上搜索 static vs self 组合:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2023-03-05
  • 1970-01-01
  • 2021-08-23
  • 2016-06-10
  • 2016-03-02
相关资源
最近更新 更多