How do I get the attributes for a model in PHP Active Record?

1.4k Views Asked by At

I want to create a new record for a model.

I would like, instead of manually specifying every field for the model, to instead iterate over the list of fields of the model, and pull the values from the post hash if they are there

e.g. (is this possible?)

  $fields = Address::attributes()  // what is the actual name of this method?
  foreach($fields as $field) {
     if($_POST[$field) {
       $input[$field] = $_POST[$field];
     }
  } 
  Address::create($input);
2

There are 2 best solutions below

1
On

Here is what I use when the HTML form fields are the same as the database fields.

if( isset($_POST['Submit']) && $_POST['Submit']=="Save") {
  $p = $_POST;
  $flds = ""; $dta=""; $tbl='dummy';
  foreach ($p as $key=>$value) {
    if( strpos("Submit ",$key) === false ) {
      if( $flds != "" ) { $flds .= ","; $dta .= ","; }
      $flds .= $key;
      $dta .= $db->escape($value);
    }
  }
  $sql = "INSERT INTO $tbl (".$flds.") VALUES (".$dta.")";
  $db->query($sql);
}
0
On

I wrote a procedure for this using Reflection. This was originally written for a Codeigniter project, but should translate well to any php-activerecord project with very little tweaking.

public static function RoutePostToModel(&$model) {

    $refClass = new ReflectionClass(get_class($model));

    if($refClass->isSubclassOf("ActiveRecord\\Model")) {

        /* This is a subclass of ActiveRecord\Model. */

        $columns = $model->attributes();

        foreach($_POST as $key => $value) {
            if(array_key_exists($key, $columns)) {
                $model->$key = $value;
            }
        }

    }

}

Whenever you want to fill your model with post data, just do something like this:

$example = new ExampleModel();
RoutePostToModel($example);
$example->save();