🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ <?php abstract class ActiveRecord { //表名 protected static $table; //参数涉及的类型 protected $fieldvalues; //查询语句 public $select; //根据一个id来查 static function findById($id) { $query = "select * from " .static::$table ." where id = $id"; return self::createDomain($query); } function __get($fieldname) { // var_dump($this);die(); return $this->fieldvalues[$fieldname]; } static function __callStatic($method, $args) { $field = preg_replace('/^findBy(\w*)$/', '${1}', $method); $query = "select * from " .static::$table ." where $field = '$args[0]'"; return self::createDomain($query); } //query查询语句,里面的todo,是做select中字段映射的 private static function createDomain($query) { //获取调用的class $klass = get_called_class(); $domain = new $klass(); $domain->fieldvalues = []; $domain->select = $query; foreach ($klass::$fields as $field => $type) { //把类中$fields数组key和value变成这个 $domain->fieldvalues[$field] = 'TODO: set from sql result'; } // var_dump($domain);die; return $domain; } } class Customer extends ActiveRecord { //查询的表名 protected static $table = 'custdb'; //涉及的类型 protected static $fields = [ 'id' => 'int', 'email' => 'varchar', 'lastname' => 'varchar' ]; } class Sales extends ActiveRecord { protected static $table = 'salesdb'; protected static $fields = [ 'id' => 'int', 'item' => 'varchar', 'qty' => 'int' ]; } assert("select * from custdb where id = 123" == Customer::findById(123)->select); assert("TODO: set from sql result" == Customer::findById(123)->email); assert("select * from salesdb where id = 321" == Sales::findById(321)->select); assert("select * from custdb where Lastname='Denoncourt'" == Customer::findByLastname('Denoncourt')->select); ~~~