I feel really limiting that only attrbutes define in the model metadata are returned when using the model toArray() method. In many occasions (especially when returning json data via my API), I need the ability add culculated/computed data to my models before returning it. We can discuss the model philosophy and if it's right to store extra data in there, but let's consider the simple example below for a second:
$oClient = $oModel->findFind(1); //... doing stuffs // adding new attribute at runtime $oClient->remaining_credits = $SomeOtherObject->calcCredit(); //... doing stuffs return $oClient->toArray()
That doesn't work, to array only returning the the attributes defined in the metaData and not "remaining_credits".
I could add the attribute in the model meta data and use the skip feature when saving/creating/updating. (https://docs.phalconphp.com/en/latest/reference/models.html#skipping-columns) . But that's some code executed all the time, across all my app, when I may need to calculate the "remaining_credits" only once.
- I could (and did till now) convert my models to arrays, to which I could easily add extar data if bneeded to. But I end up spending my time converting stuffs to array, and as a result my controlers mostly process arrays when I should be able to keep working with model till I spit the data out my api.
So I've started looking at creating a custom version of toArray() that would include "all the data" present in the current object, but I endup trying to separate meta-attribute, attributes added on the fly and all the other phalcon services (di, db...) stored in the model at initialisation... a big mess.
So does anyone has a solution for that ? Or is there something in Phalcon I missed that could let me do that ?