Quantcast
Channel: domas mituzas » php
Viewing all articles
Browse latest Browse all 4

My own database abstraction class

$
0
0

Back in 2006 July, I decided that all other database classes are not worth it, and created my own one, incorporating best features from MySQL and PHP world. It resulted in this brilliant code, which I showed to few colleagues, and got such quote:

i like your nonframework. it gives a fuzzy feeling to the poor souls that think they need an abstraction layer. — Kristian Köhntopp

This was written using TIC pattern and can be used in variety of applications:

class MyDB {
  var $conn = null;

  function MyDB($database=null,$user='root',
                $password='',$host='localhost') {
    $this->conn=mysql_connect($host,$user,$password) and
    $database?mysql_select_db($database, $this->conn):null;
  }

  function _escape($s) {
    return mysql_real_escape_string($s,$this->conn);
  }

  function _quote($s) {
    return "'" . $this->_escape($s) . "'";
  }

  function __call($method,$arguments) {
    $query=preg_replace_callback('([A-Z]|\d+)',
      create_function('$s',
         'return " ".strtolower($s[0]);'),
         $method);
    $query=str_replace(' everything ',' * ',$query);
    $first=array_shift($arguments);
    if ($first) {
      if (is_array($first)) {
        $query .= ' (' . implode(',',
                            array_map(array(&$this,'_escape'),
                            $first)) . ') ';
      } else {
        while($argument = array_shift($arguments)) {
          $first = preg_replace('/\?/',
                     $this->_quote($argument),$first,1);
        }
        $query .= $first;
      }
    }
    $ret=array();
    $res=mysql_query($query,$this->conn);
    if (!$res) { print mysql_error(); exit(); }
    while($row=mysql_fetch_assoc($res)) {
      $ret[]=$row;
    }
    return $ret;

  }
}

$x = new MyDB('test');
$x->selectEverythingFromMytableWhereIdIn(" (?,?,?) ","a'b",2,3);
$x->SelectBlahFromMytableWhereIdIn(array(1,2,3));
$x->InsertIntoBlahValues(array(1,2,3));
$x->truncateBlah();

Now I wonder where I should build community for this, Google Code or Sourceforge? Or should that be the darling MySQL Forge.

As I started digging my stuff from history, I also managed to upload my past six month pictures to flickr too – including Vienna, Taipei and few other trips.



Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images