【问题标题】:How to use DTO in this case?在这种情况下如何使用 DTO?
【发布时间】:2018-05-20 02:30:53
【问题描述】:

我的控制器中有一堆方法,现在看起来像这样:

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'));
     }
}

我想避免将大量参数传输到远程接口并将categoryId、id 和user 添加到我的ItemDTO。如果我的 ItemDTO 中有很多字段,但我只使用两个字段,这是一种好方法吗?像这样:

 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);
 }

我的 DTO 是这样的:

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
    }
}

也许我需要为每种方法使用单独的 DTO?此外,DTO 是否可以包含 $pageNumber、$pageSize 和其他过滤器等字段?这是好方法吗?

【问题讨论】:

    标签: php design-patterns architecture dto


    【解决方案1】:

    如果您只是考虑使用这两个参数,我会认为它是一个按示例查询的模式,这是相当可以接受的。因为您正在考虑添加 PageNumber 和 PageSize 之类的东西,所以我想说您已经把它搞砸了,您现在应该考虑一个单独的 ItemQuery DTO,它具有您需要的参数。

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2015-11-30
      • 2017-05-16
      • 2012-10-06
      • 2011-05-18
      • 2019-11-29
      • 2022-01-23
      • 2013-02-25
      • 1970-01-01
      相关资源
      最近更新 更多