繁体   English   中英

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

[英]Design Pattern for versioning data objects in PHP Rest API

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

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

  // getters and setters
}

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

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

  // getters and setters
}

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

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM