【问题标题】:API Upload files with metadataAPI 上传带有元数据的文件
【发布时间】:2017-10-06 08:23:06
【问题描述】:

我在这里寻求一些指导。

场景:

我有一个 Post 模型,它与 Comment 模型具有多态关系。每当我想为给定帖子创建新评论时,我都有以下端点:

$router->post('/posts/{post}/comments', 'PostsCommentsController@store');

到目前为止一切顺利。现在我想添加一个 Attachment 模型,它也是一个多态关系,因为我可能需要将附件添加到除 cmets 之外的更多事物(例如:消息等)。

我的第一个想法是按照以下方式做一些事情:

$router->post('/posts/{post}/comments/attachments', 'PostsCommentsAttachmentsController@store');

因此评论将属于帖子并带有附件。

这对我来说有点“肮脏”(尤其是控制器名称),并且需要拥有 3 个嵌套资源(可能是我想太多了)。

希望我能清楚地解释我的问题:)


以前有人遇到过这样的事情吗?你们是怎么解决的?

其他方法?我的想法完全错了吗?

对想法和建议持开放态度:D

谢谢大家。

【问题讨论】:

    标签: laravel database-design architecture polymorphism nested-resources


    【解决方案1】:

    对于每个Controllersroute,我更喜欢Single Responsibility。所以很清楚他们实际做什么和处理什么。举个例子吧:

    - Post
    /posts               -> list all post
    /posts/{id}          -> get specific post
    /posts/{id}/comments -> get comments of the post
    
    - Comment
    /comments/{id}            -> get specific comment
    /comments/{id}/attacments -> get attacments of a comment
    
    - Attachment
    /attachment/{id} -> get specific attachment
    

    对于Controller 名称,请保持简单。只需使用PostControllerCommentControllerAttachmentController。我认为这很清楚。

    【讨论】:

    • 谢谢。我的 comments 表有这两个字段:commentable_id(post_id, tasks_id, etc) 和 commentable_type( 可以是“帖子”、“任务”等的字符串)所以当我创建评论时,我需要动态知道它的类型,附件也会发生同样的情况(它可以在评论或聊天消息的上下文中)。所以我应该首先向/posts/{id}/comments 发出请求以创建并获取响应中的评论资源,然后再向 `/cmets/{id}/attachments' 发出另一个请求,以便我可以指定附件是在评论的上下文中?
    • 你的意思是提交一个帖子的评论并且评论带有附件?
    • 是的,就是这样。
    • 其实你不需要把不是每个进程都放在controller中。因为当你把它放在controller 中时,这意味着你应该通过http 请求调用它。我建议,你创建一个helper 类或helper 函数。所以你可以在任何你需要的地方调用它。即使在许多controller。我希望你能够明白。很抱歉,如果我的解释不是很清楚。
    【解决方案2】:

    经过更多的研究,我实际上意识到我想做的基本上是一个带有元数据的文件上传。

    看到这篇出色的帖子:HTTP/REST API File Uploads 解释了它

    PS:感谢 Dharma 的帮助和时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多