How to implement persistence layer in PHP

Source: Internet
Author: User
Tags hasproperty
This article mainly introduces the method of implementing the persistence layer in PHP, the interested friend's reference, hope to be helpful to everybody.

In this paper, we describe the method of implementing object persistence layer based on MySQL database in PHP. Specific as follows:

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

PHP is not commonly used, nor is it familiar to PHP, most of the content of PHP reflection is now learning.

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

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

The following code is posted:

The first is the relevant definition of the database, which defines the connection properties of the database:

<?php */  * Filename:config.php  * Created on 2012-9-29  * Created by Robintang *  to change the template For the generated file go to  * window-preferences-phpeclipse-php-code Templates *//About   database< C7/>define (' dbhost ', ' localhost '); Database server   define (' DBNAME ', ' db_wdid ');//Database name   define (' DBUSER ', ' root ');//Login username   define (' dbpswd ', ' TRB ') ); Login Password?>

Here is a simple package for database access:

<?php */* Filename:database.php * Created on 2012-9-29 * Created by Robintang * To change the template for this G   enerated 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 = '"; ";       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 above two files are written before, the persistence layer of the things are the following:

<?php */* Filename:sinorm.php * Created on 2012-11-4 * Created by Robintang * To change the template for this Gen      erated 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 ' have no [TableName] property");     } $table = $r->getstaticpropertyvalue (' tablename ');    if (! $r->hasproperty (' id ')) {throw new Exception ("Class ' $class ' have 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 ($t     b, $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 ' have no [TableName] property ");     } $table = $r->getstaticpropertyvalue (' tablename ');     if (! $r->hasproperty (' id ')) {throw new Exception ("Class ' $class ' have 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. ' and '.       "Name must has 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_sa     Veobject ($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 are examples of use:

<?php */* Filename:demo.php * Created on 2012-11-4 * Created by Robintang * To change the template for this Gener   ated file Go to * window-preferences-phpeclipse-php-code Templates */include_once ("sinorm.php"); The following is a definition of a persisted object class///each Persisted object class must have a static member called $tablename, which represents the table name of the stored object in the database//each member of the class must be initialized, that is, must give it an initial value//member variable can only be a string or integer, and please  defined as public, only the member variables of public are mapped class user{public static $tablename = ' T_user '; The static variable, the table name of the object, the public must $id = 0; The object ID, which corresponds to the primary key in the table, must be initialized to 0 public $name = '; Name, the public must be initialized $age = 0; Age, the public must be initialized $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 will automatically establish a user-corresponding table in the database $user 1 = new user ();   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//Save the $id of the ID automatically after saving = $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); Re-read the echo $user 3->name. ' <br/> ';?>

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Related recommendations:

Methods of PHP Process control and mathematical operations

PHP variables and date processing cases

Problems related to PHP garbage collection mechanism

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.