Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Object instance from Posted data - PHP

Tags:

oop

php

What is the best way of creating and populating an Object from values passed in from a form?

If for example, i have a class Car with properties Colour, Model, Make, Year and a method Save, which will either insert or update the record.

I then have a form that has fields for all these values and it is submitted. I want to create an instance of class Car with the posted values and then call the Save method. All good and well.

But what is the best way of assigning the posted values to the objects internal properties. Assuming this is a simplified scenario and the actual situation would have many more properties, making individual Set calls long-winded.

Is it best to simply call the Set method for each one? Or pass in an array to a method (or the constructor) which then calls the Set methods? Or some other way?

Any advice on best practices is appreciated

Cheers Stuart

like image 582
Stuart Avatar asked Sep 16 '09 11:09

Stuart


1 Answers

You can use a bit of Reflection magic:

public function loadFromArray($array) {
    $class = new ReflectionClass(get_class($this));
    $props = $class->getProperties();
    foreach($props as $p) {
         if (isset($array[$p->getName()])
              $p->setValue($this, $array[$p->getName]);
    }
}

You can implement this method in a base class and make all yout object inherit from that, so you have this functionality in every object without repeating yourself in any class.

like image 191
Davide Gualano Avatar answered Sep 22 '22 23:09

Davide Gualano