dtm41506 2017-12-06 09:02
浏览 248
已采纳

在这种情况下如何使用DTO?

I have a bunch of methods in my controller and now it looks like this:

class ItemController
{
     public function getItems(Request $request)
     {
         return $this->itemService->getItems($this->getUser(), $request->get('category_id'));
     }

     public function getItem(int $id, Request $request)
     {
         return $this->itemService->getItem($this->getUser(), $id, $request->get('category_id'));
     }

     public function patchItem(ItemDTO $item, Request $request)
     {
         return $this->itemService->patchItem($this->getUser(), $item, $request->get('category_id'));
     }
}

I want to avoid transfer a lot of parameters to remote interface and add categoryId, id and user to my ItemDTO. Is it good approach if I have many fields in my ItemDTO, but I use only two? Like this:

 public function getItem(int $id, Request $request)
 {
     $itemDTO = new ItemDTO($this->getUser(), $id, $request->get('category_id')); //here $title and others is empty
     return $this->itemService->getItem($itemDTO);
 }

And my DTO like this:

class ItemDTO
{
    final public $user;

    final public $id;

    final public $categoryId;

    final public $title;

    //...

    public function __construct($user = null, $id = null, $categoryId = null, $title = null, ...)
    {
       //assign variables
    }
}

Maybe I need separate DTOs for each method? Also, can DTO contains fields like $pageNumber,$pageSize and other filters? Is it good approach?

  • 写回答

1条回答 默认 最新

  • dtp0760 2017-12-06 13:40
    关注

    If you were just considering using the two parameters, I would consider it a query by example pattern, and it would be fairly acceptable. Because you are considering adding things like PageNumber & PageSize, I'd say you have blown that out, and you should now consider a separate ItemQuery DTO which has the parameters you need.

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失