How to fill an Object value automatically in php?

Asked

Viewed 394 times

5

I need a method to auto-fill my VO by receiving as parameter a mysql database result set and php’s PDO class.

Example of VO

class Pessoa{
     public $nome;
     public $idade;
}

The idea is to incorporate this fill method into my framework within a useful class.

  • You are using PDO, mysqli, mysql_* ?

  • I updated the question.

  • That one vo has some method that processes something or has only properties?

  • No it would be a simple VO. The classic POJO in java.

  • No get and set methods.

3 answers

5

With PDO you can pick up a standard object just by specifying the type of return of consultation PDO::FETCH_OBJ:

$db = new PDO('mysql:host=localhost;dbname=test','usuario','senha');
$sql = "select * from pessoas limit 5";

$stmt = $db->prepare($sql);
$stmt->execute();
$arr = $stmt->fetchAll(PDO::FETCH_OBJ);

The output is an array containing objects of the standard class the properties will have the same name as the fields that are in the database. Something more or less like this:

[0] => stdClass Object
        (
            [id_pessoa] => 1
            [nomeCompleto] => joão da silva
            [idade] => 20
        )

To access:

echo $pessoa->NomeCompleto .' - ' . $pessoa->idade;
  • Great! That’s just what I need. Thank you very much.

3


Adding the lost answer, you can still no fetchAll force to play inside your VO as follows:

$arr = $stmt->fetchAll(PDO::FETCH_CLASS, "Pessoa");

Ref: PHP manual - FETCHALL

2

Additionally I found a method that makes it follows below:

function set_object_vars($object, array $vars) {
    $has = get_object_vars($object);
    foreach ($has as $name => $oldValue) {
        $object->$name = isset($vars[$name]) ? $vars[$name] : NULL;
    }
}

Utilizing:

$a = new A();
$vars = array('one' => 234, 'two' => 2);
set_object_vars($a, $vars);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.