Skip to content

Instantly share code, notes, and snippets.

@hadashiA
Created December 10, 2012 18:32
Show Gist options
  • Save hadashiA/4252344 to your computer and use it in GitHub Desktop.
Save hadashiA/4252344 to your computer and use it in GitHub Desktop.
おれおれDataMapper
<?php
class Base_Model {
private static $db_master = null;
protected $attributes = array();
protected $is_new = true;
protected $is_dirty = false;
private $fields = array();
private $table_name = '';
private $primary_keys = array();
static function db_master() {
if (self::$db_master == null) {
self::$db_master = gf_DbConnect();
}
return self::$db_master;
}
function __set($key, $value) {
if (in_array($key, $this->fields) && $this->attributes[$key] !== $value) {
$this->attributes[$key] = $value;
$is_dirty = true;
}
}
function __get($key) {
return $this->attributes[$key];
}
function isNew() {
return $this->is_new;
}
function isDirty() {
return $this->is_dirty;
}
function save() {
if (!$this->valid()) {
return false;
}
if ($this->isNew()) {
self::db_master()->autoExecute($this->table_name,
$this->attributes,
DB_AUTOQUERY_INSERT);
} elseif ($this->isDirty()) {
$where = array();
foreach ($this->primary_keys as $field) {
$where[] = $field . ' = ' . DB::quoteSmart($this->attributes[$field]);
}
$where = implode(' AND ', $where);
self::db_master()->autoExecute($this->table_name,
$this->attributes,
DB_AUTOQUERY_UPDATE,
$where);
} else {
return true;
}
}
protected function valid() {
return false;
}
}
class Product {
private $table_name = 't_pro_product';
private $primary_keys = array('product_id', 'account_id');
private $fields = array('product_id',
'account_id',
'name',
'price',
'image_url')
function valid() {
return !is_null($this->product_id) && !is_null($this->account_id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment