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:
<?php
/
* Filename:config.php
* Created on 2012-9-29
* Created from Robintang
* To change the Templ Ate for this generated the file go to
* Window-preferences-phpeclipse-php-code Templates
*
//About Datab ASE
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:
<?php/* Filename:database.php * Created on 2012-9-29 * Created with Robintang * To change the template for
This is 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];
} array_push ($ret, $ITM);
} db_colseconnect ($con);
return $ret;
}?>
In fact, the top two files are all written before, and the persistence layer is the following:
<?php/* Filename:sinorm.php * Created on 2012-11-4 * Created by Robintang * To change the template for th
Is 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);
The 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); The 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; The 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);
The 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;
The 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); The 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);
The function Sinorm_deleteall ($class) {$TB = Sinorm_gettablename ($class);
$sql = "DELETE from ' $tb ';";
Return Sinorm_execsql ($sql);
}?>
The following examples are used:
<?php/* Filename:demo.php * Created on 2012-11-4 * Created by Robintang
Generated file go to * window-preferences-phpeclipse-php-code Templates */include_once ("sinorm.php"); The following is the definition of the class of a persisted object//each Persistent object class must have a static member called $tablename, which means that each member of the table//class that stores the object in the database must be initialized, that is, it must be given an initial value//member variable that can only be a string or an , and please define public, only the member variables of public are mapped class user{public static $tablename = ' T_user '; Static variable, the table name of the object, the required public $id = 0; The object ID, the primary key in the corresponding table, must be initialized to 0 public $name = '; Name, must initialize public $age = 0; Age, must initialize public $email = '; Must initialize}//NOTE: The following statement must be run after the definition of the class, modify the class also need to run, it completes the work of creating the table//Sinorm_resetorm (' User '); This sentence is only executed once, after execution, the User's table $user 1 = new User () is automatically established in the database.
Create an object $user 1->name = ' TRB ';
$user 1->age = 22;
$user 1->email = ' trbbadboy@qq.com '; Sinorm_saveobject ($user 1);
Save the object to the database//after saving it will automatically give the id $id = $user 1->id; Echo $iD.
' <br/> '; $user 2 = sinorm_getobject (' User ', $id); Create an object from the database by ID echo $user 2->name.
' <br/> '; $user 1->name = ' TRB '; Change the Sinorm_update ($user 1); Update to database $user 3 = sinorm_getobject (' User ', $id); Reread the Echo $user 3->name.
' <br/> ';
?>
I hope this article will help you with your PHP programming.