rikugun 发表于 2013-1-28 19:44:55

一个PHP动态数据库基础类

参考:http://www.ibm.com/developerworks/cn/opensource/os-php-flexobj/

需要PHP5支持才行,使用了__call __get __set等动态方法
class DBObject{private $id = 0;private $table;private $fields = array();function __construct( $table, $fields ){    $this->table = $table; //数据表名    foreach( $fields as $key )      $this->fields[ $key ] = null; //数据字段}function __get( $key )   //可读字段{    return $this->fields[ $key ];}function __set( $key, $value ) //可写字段{    if ( array_key_exists( $key, $this->fields ) )    {                              //添加条件可以限制某些字段不能写      $this->fields[ $key ] = $value;      return true;    }    return false;}function load( $id ){    global $db;//数据库对象    $res = $db->query("SELECT * FROM ".$this->table." WHERE ".$this->table."_id=?",      array( $id )    );    $res->fetchInto( $row, DB_FETCHMODE_ASSOC );    $this->id = $id;    foreach( array_keys( $row ) as $key )      $this->fields[ $key ] = $row[ $key ];}function insert(){    global $db;    $fields = $this->table."_id, ";    $fields .= join( ", ", array_keys( $this->fields ) );    $inspoints = array( "0" );    foreach( array_keys( $this->fields ) as $field )      $inspoints []= "?";    $inspt = join( ", ", $inspoints );$sql = "INSERT INTO ".$this->table." ( $fields )   VALUES ( $inspt )";    $values = array();    foreach( array_keys( $this->fields ) as $field )      $values []= $this->fields[ $field ];    $sth = $db->prepare( $sql );    $db->execute( $sth, $values );    $res = $db->query( "SELECT last_insert_id()" );    $res->fetchInto( $row );    $this->id = $row;    return $row;}function update(){    global $db;    $sets = array();    $values = array();    foreach( array_keys( $this->fields ) as $field )    {      $sets []= $field.'=?';      $values []= $this->fields[ $field ];    }    $set = join( ", ", $sets );    $values []= $this->id;$sql = 'UPDATE '.$this->table.' SET '.$set.' WHERE '.$this->table.'_id=?';    $sth = $db->prepare( $sql );    $db->execute( $sth, $values );}function delete(){    global $db;    $sth = $db->prepare(   'DELETE FROM '.$this->table.' WHERE '.   $this->table.'_id=?'    );    $db->execute( $sth,      array( $this->id ) );}function delete_all(){    global $db;    $sth = $db->prepare( 'DELETE FROM '.$this->table );    $db->execute( $sth );}}
继承时覆盖_construct 方法
function __construct(){parent::__construct( 'book',    array( 'author', 'title', 'publisher' ) );}
页: [1]
查看完整版本: 一个PHP动态数据库基础类