Object-Relational Mapping ORM

KISSMVC provides a "crude" class to let you map your database tables as PHP objects. Data objects that extend the crude class will gain the following 5 operations: Create, Retrieve, Update, Delete and Exists.

Say you have a database table named "users", with the following fields: uid (autoincremented primary key), username, password, fullname, created_dt. The code below shows how your "user" class can be defined:

<?php
class user extends crude {
  function 
user() {
    
//call parent with primary key name (uid) and table name (users)
    
parent::crude('uid','users');
    
//list of table fields below, need not contain all fields in table.
    
$this->rs['uid'] = '';
    
$this->rs['username'] = '';
    
$this->rs['password'] = '';
    
$this->rs['fullname'] = '';
    
$this->rs['created_dt'] = '';
  }
}
?>

With the above, you can then use code like these:

<?php
//Create
$user = new user();
$user->set('username','user');
$user->set('password','password');
$user->create();
$uid=$user->get('uid');

//Update
$user->set('password','newpassword');
$user->update();

//Retrieve, Delete, Exists
$user = new user();
$user->retrieve($uid);
if (
$user->exists())
  
$user->delete();
?>

There are currently 2 versions of the CRUDE-ORM class: one for PDO and another for mysqli.
You can grab them from the download page.

For the CRUDE-ORM to work, a global function that returns the appropriate database handle needs to be defined. For example:

<?php
//for mysqli
function getmysqli() {
  if (!isset(
$GLOBALS['mysqli'])) {
    
$GLOBALS['mysqli'] = new mysqli("localhost""username""password"'dbname');
    if (
mysqli_connect_errno())
      die(
'Cannot connect to database');
  }
  return 
$GLOBALS['mysqli'];
}

//for pdo
function getdbh() {
  if (!isset(
$GLOBALS['dbh']))
    try {
      
//$GLOBALS['dbh'] = new PDO('sqlite:'.APP_PATH.'db/dbname.sqlite');
      
$GLOBALS['dbh'] = new PDO('mysql:host=localhost;dbname=dbname''username''password');
      
$GLOBALS['dbh']->exec("SET sql_mode='ANSI_QUOTES'"); //this line is required for pdo-mysql
    
} catch (PDOException $e) {
      die(
'Connection failed: '.$e->getMessage());
    }
  return 
$GLOBALS['dbh'];
}
?>