Let's say we have Collection class Product
. Products have multiple additional variants. Let's say each variant has name and price.
class ProductVariant
{
public $name;
public $price;
}
/*
* @property string $name
* @property ProductVariant[] $variants
*/
class Product extends \Phalcon\Mvc\Collection
{
}
Then we create a product and save it:
$variant1 = new ProductVariant();
$variant2 = new ProductVariant();
$variant1->name = '...';
$variant2->name = '...';
$product = new Product();
$product->name = '...';
$product->variants = array($variant1, $variant2);
$product->save();
Model gets serialized and saved in MongoDB, there is no information about ProductVariant
. And of course when we retrieve this product from the database we get array of arrays instead of array of ProductVariant
.
Is there an easy way how we can override Phalcon ODM parsing and make it parse some properies as objects (or array of objects)?
How do you hande such case?
I have a 'beforeSave' on the ODM model, wich transforms my 'ProductVariants' to arrays, inserting the ProductVariant::class name on the model.
Then I use afterFetch
and afterSave
to transform back the arrays to 'ProductVariants' using a factory or builder whose name is composed using the class name.
Example on pseudoCode:
beforeSave:
$currentProduct = $productVariant->toArray();
$currentProduct['class'] = get_class($productVariant);
afterFetch
$builderName = $currentProduct->class.'Builder';
$builder = new $builderName();
$productVariant = $builder->create($currentProduct);
afterSave = afterFetch