模型在自身内部自称是不好的做法吗? [英] Is it bad practice for a model to call itself within itself?
本文介绍了模型在自身内部自称是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们来看一下CMS。
- 控制器通过路由获取路线并查找页面。
- 该模型提供了一个静态函数,使用路由找出ID该行正在寻找
- 模型然后使用自己执行数据库查询并返回结果
示例控制器代码
Route :: get '(。*)',function($ route)
{
$ page = Page :: load_by_route($ route);
});
示例代码
类页面扩展Eloquent {
public static function load_by_route($ route)
{
//分解路由和跟踪找到我们需要的行的实际id。
// ...一些代码行完成...
//使用我们发现的$ id执行实际查询
$ page = Page ::找到($ ID) - >首先();
返回$页面;
}
}
在您问为什么不能使用首先我们不知道这个例子中的怎么做,我只是在想知道在页面模型中使用Page ::是否不好?
解决方案
不,但约定使用 self
引用当前类:
$ page = self :: find($ id) - > first();
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?
解决方案
No, but convention says to use self
to reference the current class:
$page = self::find($id)->first();
这篇关于模型在自身内部自称是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文