简体   繁体   English

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

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

I'm just thinking of API versioning data objects.我只是在考虑 API 版本控制数据对象。 Let's say you have an object car, which looks like this in version 1 (directory v1):假设您有一辆 object 汽车,在版本 1(目录 v1)中如下所示:

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

  // getters and setters
}

In version 2, the data object changes (directory v2, $custom removed, added new property $exhaust):在版本 2 中,数据 object 发生了变化(目录 v2,移除了 $custom,添加了新属性 $exhaust):

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

  // getters and setters
}

We thought of making a "mapper" class, so that we are able to work with different versions in the business logic, eg:我们考虑制作一个“映射器”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;
  }
}

I think this approach will lead a "bloated" Mapper class and I thought there might be a better solution using a design pattern.我认为这种方法会导致“臃肿”的 Mapper class 并且我认为使用设计模式可能会有更好的解决方案。 Could we use a factory pattern here?我们可以在这里使用工厂模式吗?

I'm don't know what is your situation is but have wrote two object versions is not a best solution.我不知道你的情况是什么,但写了两个 object 版本不是最好的解决方案。 So if you have no ideas to avoid it then you of course you can use the design pattern named factory method https://refactoring.guru/design-patterns/factory-method因此,如果您不知道如何避免它,那么您当然可以使用名为工厂方法https://refactoring.guru/design-patterns/factory-method的设计模式

In your case it will be something like this在您的情况下,它将是这样的

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