【问题标题】:Design Pattern for versioning data objects in PHP Rest APIPHP Rest API 中数据对象版本控制的设计模式
【发布时间】:2021-05-07 12:55:42
【问题描述】:

我只是在考虑 API 版本控制数据对象。假设您有一个对象汽车,它在版本 1(目录 v1)中如下所示:

class Car {
  protected $color;
  protected $brand;
  protected $price;
  protected $custom;

  // getters and setters
}

在版本 2 中,数据对象发生了变化(目录 v2,移除了 $custom,添加了新属性 $exhaust):

class Car {
  protected $color;
  protected $brand;
  protected $price;
  protected $exhaust;

  // getters and setters
}

我们想制作一个“映射器”类,以便我们能够在业务逻辑中使用不同的版本,例如:

Class CarMapper extends Mapper
{
  // needs to have all member variables from all versions
  protected $color;
  protected $brand;
  protected $price;
  protected $custom;
  protected $exhaust;

  public function out($object) 
  {
    $mapperObj = new self();

    // you need to do this for each version of a data object and
    // prepare the mapperObj according the members of the object for
    // this version
    if ($object instanceof CarV1) {
      $mapperObj->color   = $object->color;
      ...
    }
    return mapperObj;
  }
}

我认为这种方法会导致“臃肿”的 Mapper 类,并且我认为使用设计模式可能会有更好的解决方案。我们可以在这里使用工厂模式吗?

【问题讨论】:

  • 只要您有 API 的并行活动版本,您的代码的某些部分就会膨胀。我给你的一条建议是不要为每次更改都制作新版本的模型类。使所有与版本相关的属性都是可选的。然后你可以有一个映射器/工厂/构建器,它只会根据请求的版本有条件地设置该属性。

标签: php rest design-patterns api-versioning


【解决方案1】:

我不知道你的情况是什么,但写了两个对象版本不是最好的解决方案。因此,如果您没有避免它的想法,那么您当然可以使用名为工厂方法的设计模式 https://refactoring.guru/design-patterns/factory-method

在你的情况下,它会是这样的

const VERSION = 1;
$app = new App(VERSION)
$car = $app->getCar();

class App 
{
    private $version;

    public function __construct($version)
    {

        if ($version === 1) {
            $this->car = new CarV1()

        } elseif ($version === 2) {
            $this->car = new CarV2()

        } else {
            //Something else

        }

        $this->version = $version;

    }

    public function getCar()
    {
        return $this->car;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 2010-10-09
    • 2016-03-08
    • 2012-05-31
    • 1970-01-01
    • 2023-03-24
    • 2018-09-30
    • 2017-03-18
    相关资源
    最近更新 更多