【发布时间】: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