How to fill a value object automatically in php?

5

I need a method that autocompletes my VO by getting a result set from the mysql database and the PDO class from php as a parameter.

Example VO

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

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

    
asked by anonymous 09.05.2014 / 21:05

3 answers

3

Adding the lost response, you can still force fetchAll to play within your VO as follows:

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

Ref: PHP Manual - FETCHALL

    
09.05.2014 / 21:29
5

With the PDO you can pick up a standard object just by specifying the query's return type 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 like this:

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

To access:

echo $pessoa->NomeCompleto .' - ' . $pessoa->idade;
    
09.05.2014 / 21:24
2

Additionally I found a method that does this as follows:

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;
    }
}

Usage:

$a = new A();
$vars = array('one' => 234, 'two' => 2);
set_object_vars($a, $vars);
    
09.05.2014 / 21:29