doukun8944 2014-01-07 05:21
浏览 74
已采纳

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

I have been using Laravel for about 2 months. And I'm just wondered about how to define models in the proper way.

For example, I define model's method in this way.

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

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

In models, I defined the methods both in static and not.

I want to know that which one is the better way to use, because Laravel seems to use a lot of static methods out there.

  • 写回答

1条回答 默认 最新

  • drhe80011 2014-01-07 08:34
    关注

    There isn't a better way. Static is necessary in some cases and in some cases it is not. If you need to call a method statically with instantiating a model object first, then it needs to be static. For example, in your controller:

    $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.
    

    Also, it looks like you are doing extra, unnecessary work. The Book object IS your model:

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

    is the same as

    Book::find($id);
    

    You shouldn't have to create any sort of public get_book($id) function. Just use Book::find($id) directly in your controller.

    http://laravel.com/docs/eloquent

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部