教材《php核心技术与最佳实践》代码清单1-3 simpleOrm.php
abstract class ActiveRecord {
protected static $table;
protected $fieldvalues;
public $select;
static function findById($id) {
$query = "select * from "
. static::$table
. " where id = $id";
return self::createDomain($query);
}
function __get($fieldname) {
return $this->fieldvalues[$fieldname];
}
static function __callStatic($method, $args) {
$field = preg_replace('/^findBy(\w*)$/', '${1}', $method);
var_dump($field);
$query = "select * from "
. static::$table
. " where $field = '$args[0]' ";
return self::createDomain($query);
}
private static function createDomain($query) {
$klass = get_called_class();
$domain = new $klass();
$domain->fieldvalues = array();
$domain->select = $query;
foreach($klass::$fields as $field => $type) {
$domain->fieldvalues[$field] = 'TODO:set from sql result';
}
return $domain;
}
}
class Customer extends ActiveRecord {
protected static $table = 'custdb';
protected static $fields = array('id' => 'int', 'email' => 'varchar', 'lastname' => 'value');
}
class Sales extends ActiveRecord {
protected static $table = 'salesdb';
protected static $fields = array('id' => 'int', 'item' => 'varchar', 'qty' => 'int');
}
/*assert("select * from custdb where id = 123" == Customer::findById(123)->select);
echo Customer::findById(123)->select;
echo '<br/>';
assert("TODO:set from sql result" == Customer::findById(123)->email);
echo Customer::findById(123)->email;
echo '<br/>';
assert("select * from salesdb where id = 321" == Sales::findById(321)->select);
echo Sales::findById(123)->select;
echo '<br/>';
assert("select * from custdb where lastname = 'Denon'" == Customer::findByLastName('Denon')->select);
echo Customer::findByLastName('Denon')->select;
echo '<br/>';*/
echo '<br/>';
Customer::findById(123)->select;
Customer::findByLastName('Denon')->select;