I started working on a way to automate creation of my database accessors. I am looking for something compatible with PHP >= 5.2. My first go at it resulted in this:
class FancyPDOBase extends PDO{
///////////////////////////////////////////////////////////////////////////////
////Magic
///////////////////////////////////////////////////////////////////////////////
public function __call($method, $args){
if(preg_match('/get[A-Z]{1}[a-z_]*[A-Z]{1}[a-z_]*By[A-Z]{1}[a-z_]*/',
$method)){
return $this->getFieldByFields($method, $args);
}else if(
preg_match('/get[A-Z]{1}[a-z_]*[A-Z]{1}[a-z_]*[A-Z]{1}[a-z_]*Array/',
$method)
){
return $this->getPairArray($method);
}//Add more expressions here.
}
///////////////////////////////////////////////////////////////////////////////
protected function getFieldByFields($method, $args){
// Create a series of value getters
preg_match('/get([A-Z]{1}.)([A-Z]{1}.)By([A-Z]{1}.*)/', $method,
$matches);
$table = strtolower($matches[1]);
$get = strtolower($matches[2]);
preg_match_all('/[A-Z]{1}[^A-Z]*/', $matches[3], $split);
$where = self::createWhereStatement($split, $args, $table);
$query = "SELECT $get FROM $table $where";
$result = $this->query($query);
if($result){
$r = $result->fetchAll();
if(count($r)==1){
return $r[0][0];
}else{
return $r;
}
}else{
return null;
}
}
//Add more methods here.
}
I am curious if there is someone who has already done this or something very similar, so I don't have to, but I'm also curious if I have missed something in thinking this would be helpful. (My general thinking is that because it extends PDO I could always fall back to a normal SQL query when I need something more complex.)