问题
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