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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With