2013-03-07 25 views
1

下面是一个使用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 ::是不是很糟糕?

+4

为什么不呢?但你可以使用'self'而不是类名 – 2013-03-07 22:09:55

回答

4

没有,但约定说,使用self引用当前类:

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

我实际上在类中使用'static :: methodName()',但不知道区别 – 2013-03-07 22:21:51

+1

@MirkoAkkov在php 5.3+中检查晚期静态绑定以了解差异在'静态'和'自我'之间 – 2013-03-07 22:22:53

+0

感谢Marko D.我刚刚开始搜索谷歌的“静态vs自我”组合:) – 2013-03-07 22:26:19

相关问题