David
David

Reputation: 59

PDO FETCH OBJECT MAPPING

I fond this example of pdo fetch_object: mysqli or PDO - what are the pros and cons?

How I can map the database cols to the class constructor? I have a lot of columns in a table and i only need some columns to contruct the object.

Is possible to be serialize object directly to database? or i need implement a method in object class?

Thanks.

Upvotes: 3

Views: 6075

Answers (1)

Sander Marechal
Sander Marechal

Reputation: 23216

I don't know any way of tying it to the constructor, but you can use magic setters and getters. Simply ignore any columns that you do not want. This works for me (tested on PHP 5.3, but should work on any PHP 5).

class MyClass
{
    // This will hold the data
    private $data = array();

    // A list of valid object properties
    private $valid_fields = array('foo', 'bar');

    // Magic setter. Silently ignore invalid fields
    public function __set($key, $value)
    {
        if (in_array($key, $this->valid_fields)) {
            $this->data[$key] = $value;
        }
    }

    // Magic getter
    public function __get($key)
    {
        if (isset($this->data[$key])) {
            return $this->data[$key];
        }
    }
}

$db = new PDO('sqlite::memory:');
$result = $db->query('SELECT 1 AS foo, 2 AS bar, 3 AS quu');
$result->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'MyClass');
var_dump($result->fetch());

Upvotes: 3

Related Questions