Is it bad practice for a model to call itself within itself?

怎甘沉沦 提交于 2019-12-24 14:38:07

问题


Here's an example, using Eloquent in Laravel.

Let's say I'm working on a CMS.

  • the controller takes the route and looks up the page via the route.
  • the model provides a static function that uses the route to figure out the id of the row it's looking for
  • the model then uses itself to perform the database query and returns the result

Example Controller Code:

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

Example Model Code:

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;
    }
}

Before you ask "Why can't you just use Page::where('route', '=', $route)->first() in the first place: I'm not wondering 'how to do' this example. I'm just wondering if it is it bad to to be using Page:: inside the page model?


回答1:


No, but convention says to use self to reference the current class:

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


来源:https://stackoverflow.com/questions/15282719/is-it-bad-practice-for-a-model-to-call-itself-within-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!