php的ar类采用后期延迟绑定实现小例子

来源:互联网 发布:手机号码在云端数据库 编辑:程序博客网 时间:2024/04/30 00:18
<?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::createInstance($query);
    }
    function __get($name) {
        return $this->fieldvalues[$name];
    }
    static function __callStatic($name, $arguments) {
        $field=  preg_replace('/^findBy(\w*)$/','{$1}', $name);//得到查询的字段条件
        $query="select * from ".static::$table." where $field='$arguments[0]'";
        return self::createInstance($query);
    }
    
    private static function createInstance($query){
        $callclass=  get_called_class();
        $instance=new $callclass();
        $instance->fieldvalues=array();//以下的部分可以执行查询并为其赋值
        $instance->select=$query;
        foreach ($callclass::$fields as $f=>$t){
            $callclass->fieldvalues[$f]=$t;
        }
        return $callclass;     
    }
}
class testmodel extends ActiveRecord{
    protected static $table='test';
    protected static $fields = array(
        //这儿的数据应该是数据库填充的
    );
}
0 0
原创粉丝点击