Created
December 10, 2012 18:32
-
-
Save hadashiA/4252344 to your computer and use it in GitHub Desktop.
おれおれDataMapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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