简体   繁体   中英

Controller “best practice” in Laravel 4

This is more of a theoretical or "best practice" question about Laravel 4, but it can be applied to the MVC pattern in general.

Say I have a website that allows users to create a "post". And so we have a Post controller which handles the creation of a new post. Now let's say that part of any given post is a video that the user uploads.

Here is my question: Should there be a separate video controller that handles the upload of the videos. (I assume there is a Video model that saves the video's filename and also which post it belongs to into a Video database table.) Or should the upload of video's be handled in the Post controller?

I ask the question because I am a little confused. It would seem to me that the MVC way would say that the video is its own entity and therefore should have its own controller. But on the other hand, the Post "owns" the video in the sense that a video is simply a part of a post, so shouldnt the Post controller handle it?

There isn't one correct way to do this, but my recommendation is to keep the uploading of the video in the post controller.

The video is "it's own thing" yes, but that doesn't mean it needs its own controller. It's another part of a post. So is the post title. So is the post text/content. So is the post timestamp, etc... Those are all "their own things" too, but they don't need to have their own controller just to manage them.

That being said, I would have a Video model and create a relationship between videos and posts.

There is no right or wrong here, maybe just conventions. If your Video is a different Entity (Model) from your Post Entity, then yes it should have its own controller. This makes it easier to recognize and helps you isolate the code.

However, this does not imply that it should have its own URL endpoint. It's perfectly fine to do something like this:

Route::get('posts/index', array('use' => 'PostsController@index'));
Route::get('posts/{id}/video', array('use' => 'VideoController@show'));

This tells the end user that a video belongs to a post, and nicely separates the logic to retrieve the models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM