开发者

Automatically creating accessor methods using PDO, __call, and preg_match

开发者 https://www.devze.com 2023-01-24 19:04 出处:网络
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:

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 FancyP开发者_如何学JAVADOBase 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.)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消