Re: [PHP-DB] About PDO::fetchObject

2015-06-11 Thread Stefan A.
Something like this should get you started

?php


// NOT TESTED !!!

class SimpleMapper
{

private $metadata = array();
private $stmt;

public function __construct(PDOStatement $stmt, array $metadata)
{
$this-stmt = $stmt;
$this-metadata = $metadata;
}

public function map()
{
$databaseData = $this-stmt-fetchObject();
$r = new \ReflectionClass($this-metadata['class']);
$obj = $r-newInstanceWithoutConstructor();

foreach ($this-metadata['c2p'] as $col = $property) {
$val = $databaseData-$col;
$type = $property['type'] ?: 'string';
settype($val, $type);

$prop = $r-getProperty($property['name']);
$prop-setAccessible(true);
$prop-setValue($val);
}

return $obj;
}

}

// usage

class Item {
public $id;
public $name;
public $description;
}

$mapper = new SimpleMapper($stmt, array(
// the class where we want to map the database data
'class' = 'Item',
// database column to object property mapping metadata
'c2p' = array(
'ItemID' = array('name' = 'id', 'type' = 'int'),
'ItemName' = array('name' = 'name', 'type' = 'string'),
'ItemDescription' = array('name' = 'description', 'type' =
'string')
)
));

$item = $mapper-map();

On Thu, Jun 11, 2015 at 9:26 AM, Octopus Puras zlk1...@gmail.com wrote:

 I have a MySQL table, whose name is Items:
 ItemID ItemName ItemDescription

 I also have a PHP class:
 class Item {
   public $id;
   public $name;
   public $description;
 }

 If I execute $stmt-fetchObject(), I will get an object with fields of
 ItemID, ItemName, etc. But I want to adapt the name of the fields to the
 Item class. What should I do?



[PHP-DB] About PDO::fetchObject

2015-06-11 Thread Octopus Puras
I have a MySQL table, whose name is Items:
ItemID ItemName ItemDescription

I also have a PHP class:
class Item {
  public $id;
  public $name;
  public $description;
}

If I execute $stmt-fetchObject(), I will get an object with fields of
ItemID, ItemName, etc. But I want to adapt the name of the fields to the
Item class. What should I do?