哪个是在Laravel中定义Model的方法的更好方法?

时间:2014-01-07 13:21:55

标签: php design-patterns laravel laravel-4

我一直在使用Laravel大约2个月。我只是想知道如何以正确的方式定义模型。

例如,我以这种方式定义模型的方法。

public static get_book_static($id){
   return Book::where($id)->first();
}

public get_book($id){
   return Book::where($id)->first();
}

在模型中,我在静态和非静态中定义了方法。

我想知道哪一个是更好的使用方法,因为Laravel似乎使用了很多静态方法。

1 个答案:

答案 0 :(得分:0)

没有更好的方法。静态在某些情况下是必要的,在某些情况下则不是。如果需要首先实例化一个模型对象静态调用一个方法,那么它需要是静态的。例如,在您的控制器中:

$myBook = Book::find($id); // find() is built into Laravel's ORM

$myBook->doSomething(); // doSomething() is a custom non-static function that you added to your Book model.

$anotherBook = Book::findSomeOtherType(); // findSomeOtherType() is a custom static function you added to the Book model.

此外,看起来你正在做额外的,不必要的工作。 Book对象是您的模型:

Book::where($id)->first();

相同
Book::find($id);

您不必创建任何类型的public get_book($id)函数。只需在控制器中直接使用Book::find($id)即可。

http://laravel.com/docs/eloquent

相关问题