I have the following sample class that maps to a MySql table (shown below). When I use PDO::FETCH_CLASS and do a *var_dump* I see that the mapping is going to all lowercase properties. i.e. 'shortName' maps to 'shortname', but should be 'shortName' (camel case, like the defined property);
Why is it mapping to all lowercase and what can I do to map them to the exact sql name coming from the SELECT?
class Category {
public $id;
public $fkId;
public $shortName;
public $longName;
public static function getCategories() {
$db = ezcDbInstance::get();
$stmt = $db->prepare('SELECT
id,
fk_id AS `fkId`,
short_name AS `shortName`,
long_name As `longName`
FROM `Category`');
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_CLASS, "Category");
}
}
Change this:
$db = ezcDbInstance::get();
$stmt = $db->prepare('SELECT...
to this:
$db = ezcDbInstance::get();
$db->setAttribute( PDO::ATTR_CASE, PDO::CASE_NATURAL );
$stmt = $db->prepare('SELECT ...
It looks like that PDO does not support uppercase letters for the member variables.
As an alternative I suggest you map the data from the database to private members of your class and you provide getter and setters for access to them:
class Category
{
private $shortname;
...
public function getShortname()
{
return $this->shortname;
}
public function setShortname($name)
{
$name = (string) $name;
if (!$name)
{
throw new InvalidArgumentException('Can\'t delete the name.');
}
$this->shortname = $name;
}
...
}
This allows you to map the fields regardless of their name and you can control if a propery can be written to or not (like the ID). These shouldn't be public anyway.
You can further on improve this by moving the data access code into a base class and extend from it for your data classes like Category or however they will be named.