PHP基于MySQL数据库实现对象持久层的方法

本文实例讲述了PHP基于MysqL数据库实现对象持久层的方法分享给大家供大家参考。具体如下:

心血来潮,做了一下PHP的对象到数据库的简单持久层。

不常用PHP,对PHP也不熟,关于PHP反射的大部分内容都是现学的。

目前功能比较弱,只是完成一些简单的工作,对象之间的关系还没法映射,并且对象的成员只能支持string或者integer两种类型的。

成员变量的值也没有转义一下。。。

下面就贴一下代码

首先是数据库的相关定义,该文件定义了数据库的连接属性

rush:PHP;">

下面是数据库访问的简单封装:

rush:PHP;"> PHP /* * Filename: database.PHP * Created on 2012-9-29 * Created by RobinTang * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ include_once("config.PHP"); $debug = false; $g_out = false; function out($s){ global $g_out; $g_out .= $s; $g_out .= "\r\n"; } function db_openconnect(){ $con = MysqL_connect(DBHOST,DBUSER,DBPSWD);
if(!<a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_set_charset("utf8",$con)){ 
  out("set <a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a> encoding fail"); 
} 
if (!$con){ 
  out('<a href="https://www.jb51.cc/tag/Could/" target="_blank" class="keywords">Could</a> not connect: ' . <a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_error()); 
} 
else{ 
  if(!<a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_select_db(<a href="https://www.jb51.cc/tag/dbn/" target="_blank" class="keywords">dbn</a>AME,$con)){ 
    $<a href="https://www.jb51.cc/tag/dbn/" target="_blank" class="keywords">dbn</a> = <a href="https://www.jb51.cc/tag/dbn/" target="_blank" class="keywords">dbn</a>AME; 
    out("<a href="https://www.jb51.cc/tag/Could/" target="_blank" class="keywords">Could</a> select database '$<a href="https://www.jb51.cc/tag/dbn/" target="_blank" class="keywords">dbn</a>' : " . <a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_error());
  } 
  $<a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a> = "set time_zone = '+8:00';"; 
  if(!db_onlyquery($<a href="https://www.jb51.cc/tag/sql/" target="_blank" class="keywords">sql</a>,$con)){ 
    out("select timezone fail!" . <a href="https://www.jb51.cc/tag/MysqL/" target="_blank" class="keywords">MysqL</a>_error()); 
  } 
} 
return $con; 

}
function db_colseconnect($con){
MysqL_close($con);
}
function db_onlyquery($sql,$con){
$r = MysqL_query($sql,$con);
if(!$r){
out("query '$sql' :fail");
return false;
}
else{
return $r;
}
}
function db_query($sql){
$con = db_openconnect();
$r = db_onlyquery($sql,$con);
$res = false;
if($r){
$res = true;
}
db_colseconnect($con);
return $r;
}
function db_query_effect_rows($sql){
$con = db_openconnect();
$r = db_onlyquery($sql,$con);
$res = false;
if($r){
$res = MysqL_affected_rows($con);
if($res==0){
$res = -1;
}
}
else{
$res = false;
}
db_colseconnect($con);
return $res;
}
function db_getresult($sql){
$con = db_openconnect();
$r = db_onlyquery($sql,$con);
$res = false;
if($r && $arr = MysqL_fetch_row($r)){
$res = $arr[0];
}
db_colseconnect($con);
return $res;
}
function db_getarray($sql){
$con = db_openconnect();
$r = db_onlyquery($sql,$con);
$ret = false;
if($r){
$row = false;
$len = 0;
$ret = Array();
$i = 0;
while($arr = MysqL_fetch_row($r)){
if($row == false || $len==0){
$row = Array();
$len = count($arr);
for($i=0;$i<$len;++$i){
$key = MysqL_field_name($r,$i);
array_push($row,$key);
}
}
$itm = Array();
for($i=0;$i<$len;++$i){
$itm[$row[$i]]=$arr[$i];
}
array_push($ret,$itm);
}
}
db_colseconnect($con);
return $ret;
}
?>

其实上面的两个文件都是之前写好的,持久层的东西是下面的:

rush:PHP;"> function SinORM_ExecSql($sql) {
return db_query($sql);
}
function SinORM_ExecArray($sql) {
return db_getarray($sql);
}
function SinORM_ExecResult($sql){
return db_getresult($sql);
}
function SinORM_GetClassPropertys($class) {
$r = new ReflectionClass($class);
if (!$r->hasProperty('tablename')) {
throw new Exception("Class '$class' has no [tablename] property");
}
$table = $r->getStaticPropertyValue('tablename');
if (!$r->hasProperty('id')) {
throw new Exception("Class '$class' has no [id] property");
}
$mpts = Array ();
$pts = $r->getProperties(ReflectionProperty :: IS_PUBLIC);
foreach ($pts as $pt) {
if (!$pt->isstatic()) {
array_push($mpts,$pt);
}
}
return Array (
$table,$mpts
);
}
function SinorM_GetPropertyString($pts,$class,$obj = false,$noid = false) {
if (is_null($pts)) {
list ($tb,$pts) = SinorM_GetClasspropertys($class);
}
$s = false;
$v = false;
$l = false;
foreach ($pts as $pt) {
$name = $pt->name;
if ($noid == false || $name != 'id') {
if ($l) {
$s = $s . ',';
}
$s = $s . $name;

    if ($obj) { 
      if ($l) { 
        $v = $v . ','; 
      } 
      $val = $pt->getValue($obj); 
      if (is_null($val)) 
        $v = $v . 'null'; 
      if (is_string($val)) 
        $v = $v . "'$val'"; 
      else 
        $v = $v . $val; 
    } 
    $l = true; 
  } 
} 
return Array ( 
  $s,$v 
); 

}
function SinorM_GetTableName($class){
$r = new ReflectionClass($class);
if (!$r->hasProperty('tablename')) {
throw new Exception("Class '$class' has no [tablename] property");
}
$table = $r->getStaticPropertyValue('tablename');
if (!$r->hasProperty('id')) {
throw new Exception("Class '$class' has no [id] property");
}
return $table;
}
function SinorM_ResetoRM($class) {
list ($tb,$pts) = SinorM_GetClasspropertys($class);
$sql = "CREATE TABLE $tb (id int NOT NULL AUTO_INCREMENT";
$r = new ReflectionClass($class);
$obj = $r->newInstance();
foreach ($pts as $pt) {
$val = $pt->getValue($obj);
$name = $pt->name;
if ($name != 'id') {
$sql = $sql . ',';
} else {
continue;
}
if (is_null($val))
throw new Exception($class . '->' . "name must have a default value");
if (is_string($val))
$sql = $sql . "$name text NULL";
else
$sql = $sql . "$name int NULL";
}
$sql = $sql . ",PRIMARY KEY (id));";
$dsql = "DROP TABLE IF EXISTS $tb;";
return SinorM_Execsql($dsql) && SinorM_Execsql($sql);
}
function SinorM_SaveObject($obj) {
$class = get_class($obj);
list ($tb,$pts) = SinorM_GetClasspropertys($class);
list ($names,$vals) = SinorM_GetPropertyString($pts,$obj,true);
$sql = "INSERT INTO $tb($names) values($vals)";
if(SinorM_Execsql($sql)){
$q = "SELECT id FROM $tb ORDER BY id DESC LIMIT 1;";
$id = SinorM_ExecResult($q);
if($id){
$obj->id = $id;
}
}
return false;
}
function SinorM_Getobjects($class) {
list ($tb,$pts) = SinorM_GetClasspropertys($class);
$sql = "SELECT from $tb;";
$ary = SinorM_ExecArray($sql);
$res = false;
if (is_array($ary)) {
$res = Array ();
$ref = new ReflectionClass($class);
foreach ($ary as $a) {
$obj = $ref->newInstance();
foreach ($pts as $pt) {
$name = $pt->name;
$olv = $pt->getValue($obj);
$val = $a[$name];
if (is_string($olv))
$pt->setValue($obj,$val);
else
$pt->setValue($obj,intval($val));
}
array_push($res,$obj);
}
} else {
echo 'no';
}
return $res;
}
function SinorM_Getobject($class,$id) {
list ($tb,$pts) = SinorM_GetClasspropertys($class);
$sql = "SELECT
from $tb where id=$id;";
$ary = SinorM_ExecArray($sql);
$res = null;
if (is_array($ary) && count($ary) > 0) {
$res = Array ();
$ref = new ReflectionClass($class);
$a = $ary[0];
$obj = $ref->newInstance();
foreach ($pts as $pt) {
$name = $pt->name;
$olv = $pt->getValue($obj);
$val = $a[$name];
if (is_string($olv))
$pt->setValue($obj,$val);
else
$pt->setValue($obj,intval($val));
}
return $obj;
}
return null;
}
function SinorM_Update($obj) {
$class = get_class($obj);
list ($tb,$pts) = SinorM_GetClasspropertys($class);
$sql = "UPDATE $tb SET ";
$l = false;
foreach ($pts as $pt) {
$name = $pt->name;
$val = $pt->getValue($obj);
if ($name == 'id')
continue;
if ($l)
$sql = $sql . ',';
if (is_string($val))
$sql = $sql . "$name='$val'";
else
$sql = $sql . "$name=$val";
$l = true;
}
$sql = $sql . " WHERE id=$obj->id;";
return SinorM_Execsql($sql);
}
function SinorM_SaveOrUpdate($obj) {
if (SinorM_Getobject(get_class($obj),$obj->id) == null) {
SinorM_SaveObject($obj);
} else {
SinorM_Update($obj);
}
}
function SinorM_DeleteObject($obj){
$class = get_class($obj);
$tb = SinorM_GetTableName($class);
$sql = "DELETE FROM $tb WHERE id=$obj->id;";
return SinorM_Execsql($sql);
}
function SinorM_Deleteall($class){
$tb = SinorM_GetTableName($class);
$sql = "DELETE FROM $tb;";
return SinorM_Execsql($sql);
}
?>

下面是使用的例子:

rush:PHP;"> public $name = ''; // 姓名,必须初始化 public $age = 0; // 年龄,必须初始化 public $email = ''; // 必须初始化

}

// 注意:下面的语句一定要在定义好类之后运行一下,修改了类也需要运行一下,它完成创建表的工作
// SinORM_ResetORM('User'); // 这一句只是一开始执行一次,执行之后就会自动在数据库中建立User对应的表

$user1 = new User(); // 创建一个对象
$user1->name = 'TRB';
$user1->age = 22;
$user1->email = 'trbbadboy@qq.com';
SinorM_SaveObject($user1); // 把对象保存到数据库

// 保存之后会自动给id的
$id = $user1->id;
echo $id . '
';

$user2 = SinorM_Getobject('User',$id); // 通过ID从数据库创建一个对象
echo $user2->name . '
';

$user1->name = 'trb'; // 改变一下
SinorM_Update($user1); // 更新到数据库

$user3 = SinorM_Getobject('User',$id); // 重新读出
echo $user3->name . '
';
?>

希望本文所述对大家的PHP程序设计有所帮助。

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...