A method of implementing object persistence layer in PHP based on MySQL database

Source: Internet
Author: User
Tags foreach config count hasproperty php programming mysql database

This article illustrates the method of implementing object persistence layer based on MySQL database in PHP. Share to everyone for your reference. Specifically as follows:

Whim, did a bit of PHP object to the database simple persistence layer.

PHP is not commonly used, but also not familiar with PHP, about the most of the content of PHP reflection is now learned.

At present, the function is weak, just do some simple work, the relationship between objects can not be mapped, and the members of the object only support string or integer two types.

The value of the member variable is also not escaped ...

Here's how to paste the code:

The first is the relevant definition of the database that defines the connection properties for the database:

?
1 2 3 4 5 6 7 8 9 10 11 12 13-14 <?php/* Filename:config.php * Created on 2012-9-29 * Created with Robintang * To change the template for this Generat Ed 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 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 112 113 114 &lt;?php/* Filename:database.php * Created on 2012-9-29 * Created with Robintang * To change the template for this gene Rated 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, D Buser, DBPSWD); &nbsp; if (!mysql_set_charset ("UTF8", $con)) {out ("Set MySQL encoding Fail");} if (! $con) {out (' could not connect: '. Mys Ql_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 '); 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 &amp;&amp; $arr = Mysql_fetch_row ($r)) {$res = $arr [0];} db_colseconnect ($con); return $res; The 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 &lt; $len; + $i) {$key = Mysql_field_name ($r, $i); Array_push ($row, $key);}} $ITM = Array (); For ($i =0 $i &lt; $len + + $i) {$itm [$row [$i] $arr [$i];} array_push ($ret, $ITM); } db_colseconnect ($con); return $ret; }?&gt;

In fact, the above two files are written before, the persistence layer of things are the following:

?
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 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 5, 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 11 9 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-18 0 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 &lt;?php/* Filename:sinorm.php * Created on 2012-11-4 * Created with Robintang * To change the template for this genera Ted file Go to * window-preferences-phpeclipse-php-code Templates */include_once ("database.php"); &nbsp; 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 REFL Ectionclass ($class); if (! $r-&gt;hasproperty (' tablename ')) {throw new Exception ("Class ' $class ' has no [TableName] property");} $table = $r-& Gt;getstaticpropertyvalue (' tablename '); if (! $r-&gt;hasproperty (' id ')) {throw new Exception (' Class ' $class ' has no [ID] property];} $mpts = Array (); $pts = $r-&gt;getproperties (reflectionproperty:: Is_public); foreach ($pts as $pt) {if (! $pt-&gt;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 = Fals E $l = false; foreach ($pts as $pt) {$name = $pt-&gt;name; if ($noid = = False | | $name!= ' ID ') {if ($l) {$s = $s. ','; } $s = $s. $name; &nbsp; if ($obj) {if ($l) {$v = $v. ','; $val = $pt-&gt;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); The function Sinorm_gettablename ($class) {$r = new Reflectionclass ($class); if (! $r-&gt;hasproperty (' tablename ')) {throw n EW Exception ("Class ' $class ' has no [TableName] property"); $table = $r-&gt;getstaticpropertyvalue (' tablename '); if (! $r-&gt;hasproperty (' id ')) {throw new Exception ("Class ' $class ' has no [id]");} 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-&gt;newinstance (); foreach ($pts as $pt) {$val = $pt-&gt;getvalue ($obj); $name = $pt-&gt;name; if ($name!= ' id ') {$sql = $sql. ','; else {Continue} if (Is_null ($val)) throw new Exception ($class. '-&gt; '. "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) &amp;&amp; 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 ' $TB ' ORDER by ' id ' DESC LIMIT 1; '; $id = Sinorm_execresult ($q); if ($id) { $obj-&gt;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-&gt;newinsta NCE (); foreach ($pts as $pt) {$name = $pt-&gt;name; $olv = $pt-&gt;getvalue ($obj); $val = $a [$name]; if (is_string ($OLV)) $pt-&G T;setvalue ($obj, $val); else $pt-&gt;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) &amp;&amp; count ($ary) &gt; 0) {$res = array (); $ref = new Reflectionclass ($class); $a = $ary [0]; $ob j = $ref-&gt;newinstance (); foreach ($pts as $pt) {$name = $pt-&gt;name; $olv = $pt-&gt;getvalue ($obj); $val = $a [$name]; if (is_string ($OLV)) $pt-&G T;setvalue ($obj, $val); else $pt-&gt;setvalue ($obj, Intval ($val)); Return $obj return null; function Sinorm_update ($obj) {$class = Get_class ($obj); list ($TB, $pts) = Sinorm_getclasspropertys ($class); $sql = "Up DATE ' $TB ' SET '; $l = false; foreach ($pts as $pt) {$name = $pt-&gt;name; $val = $pt-&gt;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-&gt;id;"; Return Sinorm_execsql ($sql); The function sinorm_saveorupdate ($obj) {if Sinorm_getobject (Get_class ($obj), $obj-&gt;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-&gt;id;; Return Sinorm_execsql ($sql); function Sinorm_deleteall ($class) {$TB = Sinorm_gettablename ($class); $sql = "DELETE from ' $tb ';"; return Sinorm_execsql ($sql); }?&gt;

The following examples are used:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The

I hope this article will help you with your PHP programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.