开发者

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,开发者_StackOverflow社区 or does it require an additional framework?


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();


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)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜