简体   繁体   English

Laravel 4中的控制器“最佳实践”

[英]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. 这更多是关于Laravel 4的理论或“最佳实践”问题,但通常可以将其应用于MVC模式。

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. 因此,我们有一个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? (我假设有一个Video模型可以将视频的文件名及其所属的发布保存到Video数据库表中。)还是应该在Post控制器中处理视频的上传?

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. 在我看来,MVC方式会说视频是其自己的实体,因此应该具有自己的控制器。 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? 但另一方面,从某种意义上来说,视频只是视频的一部分,因此该视频“拥有”该视频,因此,该Post控制器应该处理该视频吗?

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. 如果您的VideoPost实体是不同的实体(模型),则可以,它应该具有自己的控制器。 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. 但是,这并不意味着它应该具有自己的URL端点。 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. 这告诉最终用户视频属于帖子,并且很好地分离了逻辑以检索模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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