1

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.)

hakre
  • 193,403
  • 52
  • 435
  • 836
fncomp
  • 6,040
  • 3
  • 33
  • 42

1 Answers1

1

Sounds like you're building the beginnings of an ORM. Which means it's time for the obligatory link to:

http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx

Ross Snyder
  • 1,945
  • 11
  • 11
  • Thanks, looks like I'm reinventing the wheels listed here: http://stackoverflow.com/questions/108699/good-php-orm-library. I was concerned about the diminishing returns problem from the get go, but good to know it is not just my lack of know how that had me concerned. – fncomp Nov 14 '10 at 05:11