3

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.

Community
  • 1
  • 1
David
  • 59
  • 1
  • 2

1 Answers1

3

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());
Sander Marechal
  • 22,978
  • 13
  • 65
  • 96
  • I thought there was some automatic method. Do you know any slution to serialize object directly to database? – David Feb 22 '11 at 16:07
  • You can't with straight PDO. If you want automation, have a look at some of the ORM libraries for PHP, like Doctrine, Proper or Idiorm. They can do this. – Sander Marechal Feb 23 '11 at 22:55