tags:

views:

60

answers:

4

I do a lot of ASP.NET MVC 2 development, but I'm tackling a small project at work and it needs to be done in PHP.

Is there anything built-in to PHP to do model binding, mapping form post fields to a class? Some of my PHP code currently looks like this:

class EntryForm
{
    public $FirstName = "";
    public $LastName = "";
}

    $EntryForm = new EntryForm();

if ($_POST && $_POST["Submit"] == "Submit")
{
    $EntryForm->FirstName = trim($_POST["FirstName"]);
    $EntryForm->LastName = trim($_POST["LastName"]);
}

Is there anything built-in to a typical PHP install that would do such mapping like you'd find in ASP.NET MVC, or does it require an additional framework?

A: 

Built in to PHP? No.

The framework answer you hint at is where you'll need to go for this one (after all, ASP.NET is a framework too)

Peter Bailey
A: 

Nothing built into PHP for this. But easy to implement in your EntryForm class. You could add public function populate($post) to EntryForm and pass it the $_POST variable. It would loop through and if the class attribute exists, set it. In fact, you could build an abstract class that implements populate() and extend it with your EntryForm, or any other form you want. You'll want to sanitize the input as well, of course.

thetaiko
A: 

Not native but a better solution that permits you using your own classes or a standard class ...

function populateWithPost ($obj = NULL)
{
  if(is_object($obj)) {

  } else {
      $obj = new StdClass ();
  }

  foreach ($_POST as $var => $value) {
      $obj->$var = trim($value); //here you can add a filter, like htmlentities ...
  }

  return $obj;
}

And then you can use it like:

class EntryForm
{
    public $FirstName = "";
    public $LastName = "";
}

$entry = getPostObject ($entry);

or

 $obj = getPostObject ();
Mahomedalid
Thanks! One small change and it worked perfectly.foreach ($_POST as $key => $value) { $obj->$key = trim($value); }
Pete Nelson
Sorry! Thanks, I fix it! :)
Mahomedalid
A: 
corprew
yes, I think that a complete ORM layer is a best solution.
Mahomedalid