PHP基于MySQL数据库实现对象持久层的方法
程序员文章站
2022-07-08 08:16:19
本文实例讲述了php基于mysql数据库实现对象持久层的方法。分享给大家供大家参考。具体如下:
心血来潮,做了一下php的对象到数据库的简单持久层。
不常用php,对p...
本文实例讲述了php基于mysql数据库实现对象持久层的方法。分享给大家供大家参考。具体如下:
心血来潮,做了一下php的对象到数据库的简单持久层。
不常用php,对php也不熟,关于php反射的大部分内容都是现学的。
目前功能比较弱,只是完成一些简单的工作,对象之间的关系还没法映射,并且对象的成员只能支持string或者integer两种类型的。
成员变量的值也没有转义一下。。。
下面就贴一下代码:
首先是数据库的相关定义,该文件定义了数据库的连接属性:
<?php /* * filename: config.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 */ // about database define('dbhost', 'localhost'); // 数据库服务器 define('dbname', 'db_wdid'); // 数据库名称 define('dbuser', 'root'); // 登陆用户名 define('dbpswd', 'trb'); // 登录密码 ?>
下面是数据库访问的简单封装:
<?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(!mysql_set_charset("utf8", $con)){ out("set mysql encoding fail"); } if (!$con){ out('could not connect: ' . mysql_error()); } else{ if(!mysql_select_db(dbname, $con)){ $dbn = dbname; out("could select database '$dbn' : " . mysql_error()); } $sql = "set time_zone = '+8:00';"; if(!db_onlyquery($sql, $con)){ out("select timezone fail!" . mysql_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; } ?>
其实上面的两个文件都是之前写好的,持久层的东西是下面的:
<?php /* * filename: sinorm.php * created on 2012-11-4 * created by robintang * to change the template for this generated file go to * window - preferences - phpeclipse - php - code templates */ include_once("database.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, $class, $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); } ?>
下面是使用的例子:
<?php /* * filename: demo.php * created on 2012-11-4 * created by robintang * to change the template for this generated file go to * window - preferences - phpeclipse - php - code templates */ include_once("sinorm.php"); // 下面是一个持久对象的类的定义 // 每个持久对象类都必须有一个叫做$tablename静态成员,它表示数据库中存储对象的表名 // 类的每个成员都必须初始化,也就是必须给它一个初始值 // 成员变量只能为字符串或者整型,而且请定义成public的,只有public的成员变量会被映射 class user{ public static $tablename = 't_user'; // 静态变量,对象的表名,必须的 public $id = 0; // 对象id,对应表中的主键,必须的,而且必须初始化为0 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 . '<br/>'; $user2 = sinorm_getobject('user', $id); // 通过id从数据库创建一个对象 echo $user2->name . '<br/>'; $user1->name = 'trb'; // 改变一下 sinorm_update($user1); // 更新到数据库 $user3 = sinorm_getobject('user', $id); // 重新读出 echo $user3->name . '<br/>'; ?>
希望本文所述对大家的php程序设计有所帮助。
上一篇: 如何使用Python做个自定义动态壁纸
推荐阅读