[英]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.