2

I am using Fat Free PHP to return a query using a join. Because of this the results have extra fields from another table. I want to be able to convert the array to objects (ie arrayToObjects) but I want the additional fields to persist. I would also like this to return an instance of my class, not an stdClass.

I tried adding the additional fields to the php model but it loses the values when I pass the mysql result into arrayToObjects().

Is this achievable?

Jeremy
  • 3,620
  • 9
  • 43
  • 75
  • Check SO link for your answer http://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php – ahPo May 13 '16 at 14:41
  • This works for converting to an stdClass, but what if I want it to be an instance of my model class? @ahPo – Jeremy May 13 '16 at 14:48
  • [Here's a few answers about converting the `stdClass` to another `Class`](http://stackoverflow.com/questions/3243900/convert-cast-an-stdclass-object-to-another-class). (Most use Reflection.) – ourmandave May 14 '16 at 01:15
  • Probably to late, but Fat Free has an [abstract interface called Magic](http://fatfreeframework.com/magic) that let's you treat your extended class like an array. – ourmandave May 18 '16 at 01:35

3 Answers3

1

This is a simple but dirty trick I learned some time ago.

// Create an array
$array = range('a', 'z');

// Convert array to object
$object = json_decode(json_encode($array));

And voila! An object with all the values you want it to have. Nothing fancy about it.

Peter
  • 8,776
  • 6
  • 62
  • 95
  • This does work. But I was hoping to have an instance of my object not an stdClass. Would the best route just to be create a new mapper? – Jeremy May 13 '16 at 14:45
1

I am not huge fan of my eventual solution but I added the values manually to the object from the array.

For example:

object = new Object();
object->id = array['id']
object->name = array['name']
Jeremy
  • 3,620
  • 9
  • 43
  • 75
0

You could add a custom setter and getter method to you model, so it can load and save your extra arrays/objects. That's probably the easiest way for you now. You can also try to use the F3 cortex orm, which has support for relations built in.

ikkez
  • 2,052
  • 11
  • 20