Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomatically creating accessor methods using PDO, __call, and preg_match
    primarykey
    data
    text
    <p>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: <code><pre>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}.<em>)([A-Z]{1}.</em>)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. } </pre></code></p> <p>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.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload