The Model ORM (Object-Relational Mapping)

KISSMVC provides a "Model" ORM class to let you map your database tables as PHP objects. It is built on PDO and thus requires PHP5.

Data objects that extend the Model 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 Model {
  function 
User() {
    
//call parent with primary key name "uid", table name "users"
    //and function that returns the pdo handler named "getdbh"
    
parent::__construct('uid','users','getdbh');
    
//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'] = '';
  }
}
?>

For the Model to work, a global function that returns the appropriate PDO database handle needs to be defined. For example:

<?php
//To release the database connection simply do:
//$GLOBALS['dbh']=null;
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');
    } catch (
PDOException $e) {
      die(
'Connection failed: '.$e->getMessage());
    }
  return 
$GLOBALS['dbh'];
}
?>

KISSMVC is designed this way so that you can also use the above function for your other database needs.

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();

//Retrieve based on other criteria than the PK
$user = new User();
$user->retrieve_one("username=?",'erickoh');
$user->retrieve_one("username=? AND password=? AND status='enabled'",array('erickoh','123456'));

//Return an array of Model objects
$user = new User();
$user_array $user->retrieve_many("username LIKE ?",'eric%');
foreach (
$user_array as $user)
  
$user->delete();

//Return selected fields as array
$user = new User();
$result_array $user->select("username,email","username LIKE ?",'eric%');
print_r($result_array);
?>