Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP form post, automatically mapping to an object (model binding)

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?

like image 905
Pete Nelson Avatar asked Jun 02 '10 14:06

Pete Nelson


3 Answers

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 = populateWithPost(new EntryForm());

or

 $obj = populateWithPost();
like image 87
Mahomedalid Avatar answered Nov 15 '22 17:11

Mahomedalid


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)

like image 43
Peter Bailey Avatar answered Nov 15 '22 17:11

Peter Bailey


What you're looking for is an ORM (Object Relationship Mapping) layer. PHP has a couple, one of which is Doctrine. That said, mahomedalidp's answer is very handy for getting things done in PHP.

like image 35
corprew Avatar answered Nov 15 '22 17:11

corprew