PHP Rest API 中数据对象版本控制的设计模式

问题描述

我只是在考虑 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 类,我认为使用设计模式可能会有更好的解决方案。我们可以在这里使用工厂模式吗?

解决方法

我不知道你的情况是什么,但写了两个对象版本并不是最好的解决方案。因此,如果您没有避免它的想法,那么您当然可以使用名为工厂方法的设计模式 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;
    }

}