I'm trying to build an API wrapper class, that sends requests in a JSON format. the sample request format is something like this:
{
"items": [
{
"brand": "brand",
"idCategory": "idCategory",
"idItem": "idItem",
"attributes": [
{
"idUda": "idUda",
"price": "price"
},
{
"idUda": "idUda",
"price": "price"
}
],
"description": "description",
"skus": [
{
"price": {
"offer": "offer",
"default": "default"
},
"stock": {
"available": "available",
"amount": "amount"
},
"gtin": "gtin",
"images": [
"image",
"image"
],
"idSku": "idSku",
}
]
}
]
}
My first thought was to create an object for each element of the JSON request that is an array, something like this:
$attr1 = new Attribute;
$attr1->setIdUda('xxx')
->setPrice('99999');
$price = new Price;
$price->setOffer('teste')
->setDefault('99.99');
$stock = new Stock;
$stock->setAvailable(true)
->setAmount('9999');
$product = new Product;
$product->setBrand('Apple')
->setIdCategory('500')
->setIdItem('9999')
->setAttributes($attr1)
->setDescription('nice product')
->setSkus($price);
->setSkus($stock);
And each one these objects have a toArray()
method, that returns an associative array, e.g.:
class Price {
//getters and setters....
function toArray() {
return array(
'offer' => $this->offer,
'default' => $this->default
)
}
}
Inside of the Product
class all these attributes setters are grouped to form an array so I can convert it to the JSON format later.
class Product {
//.....
public function setAttributes(Attribute $attributes) {
$this->attributes['attributes'][] = $attributes->toArray();
return $this;
}
}
But it still feels like it's highly coupled, because i have to set the key of each one of these arrays, in order to form the JSON data.
What would be the "best" approach to make this code easier to maintain? Should I use classes only for some attributes?