We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Overriding Resultset\Simple::toArray() to also call Model::toArray() on each result row


Can I somehow override the toArray() function in Phalcon\Mvc\Model\Resultset\Simple from within PHP?

I'm trying to extend it so that instead of returning it's _rows array directly, it turns each of it's rows into a model instance (like what happens when you iterate the resultset) and calls toArray() on each row and returns those results.

This means that I can overwrite the toArray in my base model to 'enhance' certain fields, and automatically have all records returned in the Resultsets' toArray() function also be enhanced too.

This makes the Resultset returned by Model::find() function a lot more useful because I don't have to manually loop and toArray each row to get my enhanced result.

I'm not sure if overriding the function is even the best approach but I hope my intentions are clear.

Well in shrot:

You have to create your own Resultset which will extends already exiting phalcons and override toArray() which will do foreach for all rows and toArray(). Then you have to change find method in your model to return your class.


Maybe look into "hydration modes" - you can set up find() to return the results as an array rather than models - without needing to override the default find().