Home >Backend Development >PHP Tutorial >PHP method to implement object persistence layer based on MySQL database_PHP tutorial
This article describes the example of PHP’s method of implementing the object persistence layer based on the MySQL database. Share it with everyone for your reference. The details are as follows:
On a whim, I made a simple persistence layer from PHP objects to the database.
I don’t often use PHP, and I am not familiar with PHP. Most of the content about PHP reflection is learned now.
Currently, the function is relatively weak. It only completes some simple tasks. The relationship between objects cannot be mapped, and the members of the object can only support two types: string or integer.
The values of member variables are not escaped. . .
Post the code below:
The first is the relevant definition of the database. This file defines the connection properties of the database:
?
|
<🎜>/*<🎜> <🎜>* 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'); // Database server<🎜> <🎜>define('DBNAME', 'db_wdid'); // Database name<🎜> <🎜>define('DBUSER', 'root'); // Login username<🎜> <🎜>define('DBPSWD', 'trb'); // Login password<🎜> <🎜>?> |
The following is a simple encapsulation of database access:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
/* * 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 .= "rn"; } 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; } ?> |
In fact, the two files above were written before, and the persistence layer is as follows:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
/* * 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); } ?> |
The following is an example of usage:
?
3 45 12 13 |
<🎜>/*<🎜>
<🎜>* 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");<🎜>
<🎜>//The following is the definition of a persistent object class<🎜>
<🎜> // Each persistent object class must have a static member called $tablename, which represents the name of the table where the object is stored in the database <🎜>
<🎜>// Each member of the class must be initialized, that is, it must be given an initial value <🎜>
<🎜>// Member variables can only be strings or integers, and please define them as public. Only public member variables will be mapped <🎜>
<🎜>class User{<🎜>
<🎜>public static $tablename = 't_user'; // Static variable, table name of the object, required<🎜>
<🎜>public $id = 0; // Object ID, corresponding to the primary key in the table, is required and must be initialized to 0<🎜>
<🎜> <🎜>
<🎜>public $name = ''; // Name, must be initialized<🎜>
<🎜>public $age = 0; // Age, must be initialized<🎜>
<🎜>public $email = ''; // Must be initialized<🎜>
<🎜>}<🎜>
<🎜> <🎜>
<🎜>// Note: The following statement must be run after the class is defined. You also need to run it after modifying the class. It completes the work of creating the table <🎜>
<🎜>// SinORM_ResetORM('User'); // This sentence is only executed once at the beginning. After execution, the table corresponding to User will be automatically created in the database <🎜>
<🎜> <🎜>
<🎜>$user1 = new User(); // Create an object<🎜>
<🎜>$user1->name = 'TRB';
$user1->age = 22;
$user1->email = 'trbbadboy@qq.com';
SinORM_SaveObject($user1); // Save the object to the database
//The ID will be automatically given after saving
$id = $user1->id;
echo $id . ' '; $user2 = SinORM_GetObject('User', $id); // Create an object from the database by ID echo $user2->name . ' '; $user1->name = 'trb'; // Change it SinORM_Update($user1); // Update to database $user3 = SinORM_GetObject('User', $id); // Re-read echo $user3->name . ' '; ?> |