How PHP implements the object persistence layer based on MySQL database

Source: Internet
Author: User
Tags hasproperty
This article mainly introduces how to implement the object persistence layer in PHP based on MySQL database. The example analyzes the related skills of php to implement the persistence layer, for more information about how to implement the object persistence layer in PHP based on MySQL databases, see the following example. Share it with you for your reference. The details are as follows:

After a whim, I made a bit of PHP objects to the simple persistent layer of the database.

PHP is not commonly used and is not familiar with PHP. most of the content about PHP Reflection is learned now.

Currently, the functions are relatively weak, but some simple work is completed. The relationship between objects cannot be mapped, and the object members can only support the string or integer types.

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

The following code is provided:

The first is the definition of the database. This File defines the connection attributes of the database:

<? 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'); // 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 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;   } ?> 

In fact, the above two files are written previously, and the persistent layer is as follows:

<?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);   } ?> 

The following is an example:

<? 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 "); // The following is the definition of a persistent object class // Each persistent object class must have a static member called $ tablename, it indicates that every member of the table name/class of the object stored in the database must be initialized, that is, it must be given an initial value // The member variable can only be a string or an integer, and define it as public. only the public member variables will be mapped to class User {public static $ tablename = 't_ user'; // static variables, table name of the object, required public $ id = 0; // object ID, corresponding to the primary key in the table, required, and must be initialized to 0 public $ name = ''; // name, public $ age = 0; // age; public $ email = ''must be initialized; // Initialization required} // note: the following statement must be run after the class is defined. if you modify the class, you must run it to create a table. // SinORM_ResetORM ('user '); // This statement is executed only once at the beginning. after execution, the table $ user1 = new User () corresponding to the User is automatically created in the database (); // create an object $ user1-> name = 'trb'; $ user1-> age = 22; $ user1-> email = 'trbbadboy @ qq.com '; sinORM_SaveObject ($ user1); // Save the object to the database. // after saving the object, the $ id = $ user1-> id; echo $ id will be automatically assigned to the id.'
'; $ User2 = SinORM_GetObject ('user', $ id); // create an object from the database by ID echo $ user2-> name .'
'; $ User1-> name = 'trb'; // change SinORM_Update ($ user1); // update to database $ user3 = SinORM_GetObject ('user', $ id ); // read echo $ user3 again-> name.'
';?>

I hope this article will help you with php programming.

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.