>  기사  >  백엔드 개발  >  PHP에서 지속성 레이어를 구현하는 방법

PHP에서 지속성 레이어를 구현하는 방법

墨辰丷
墨辰丷원래의
2018-06-09 16:35:421685검색

이 글은 주로 PHP에서 지속성 레이어를 구현하는 방법을 소개합니다. 관심 있는 친구들이 참고하면 도움이 될 것입니다.

이 문서의 예에서는 PHP가 MySQL 데이터베이스를 기반으로 개체 지속성 계층을 구현하는 방법을 설명합니다. 자세한 내용은 다음과 같습니다.

기분에 PHP 객체에서 데이터베이스까지 간단한 지속성 레이어를 만들었습니다.

저는 PHP를 자주 사용하지 않고, PHP에 익숙하지도 않습니다. 이제 PHP 리플렉션에 대한 내용은 대부분 배웠습니다.

현재 이 함수는 일부 간단한 작업만 완료할 수 있으며 개체 간의 관계는 매핑할 수 없으며 개체의 구성원은 문자열 또는 정수의 두 가지 유형만 지원할 수 있습니다.

멤버 변수의 값은 이스케이프되지 않습니다. . .

코드는 아래에 게시되어 있습니다.

첫 번째는 데이터베이스의 관련 정의입니다. 이 파일은 데이터베이스의 연결 속성을 정의합니다.

<?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(&#39;DBHOST&#39;, &#39;localhost&#39;); // 数据库服务器 
  define(&#39;DBNAME&#39;, &#39;db_wdid&#39;); // 数据库名称 
  define(&#39;DBUSER&#39;, &#39;root&#39;); // 登陆用户名 
  define(&#39;DBPSWD&#39;, &#39;trb&#39;); // 登录密码 
?>

다음은 데이터베이스 액세스의 간단한 캡슐화입니다.

<?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(&#39;Could not connect: &#39; . mysql_error()); 
    } 
    else{ 
      if(!mysql_select_db(DBNAME, $con)){ 
        $dbn = DBNAME; 
        out("Could select database &#39;$dbn&#39; : " . mysql_error());
      } 
      $sql = "set time_zone = &#39;+8:00&#39;;"; 
      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 &#39;$sql&#39; :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; 
  } 
?>

실제로 두 개는 위의 파일은 이전에 작성된 것입니다. 지속성 레이어는 다음과 같습니다.

<?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(&#39;tablename&#39;)) { 
      throw new Exception("Class &#39;$class&#39; has no [tablename] property"); 
    } 
    $table = $r->getStaticPropertyValue(&#39;tablename&#39;); 
    if (!$r->hasProperty(&#39;id&#39;)) { 
      throw new Exception("Class &#39;$class&#39; 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 != &#39;id&#39;) { 
        if ($l) { 
          $s = $s . &#39;,&#39;; 
        } 
        $s = $s . $name; 
   
        if ($obj) { 
          if ($l) { 
            $v = $v . &#39;,&#39;; 
          } 
          $val = $pt->getValue($obj); 
          if (is_null($val)) 
            $v = $v . &#39;null&#39;; 
          if (is_string($val)) 
            $v = $v . "&#39;$val&#39;"; 
          else 
            $v = $v . $val; 
        } 
        $l = true; 
      } 
    } 
    return Array ( 
      $s, 
      $v 
    ); 
  } 
  function SinORM_GetTableName($class){ 
    $r = new ReflectionClass($class); 
    if (!$r->hasProperty(&#39;tablename&#39;)) { 
      throw new Exception("Class &#39;$class&#39; has no [tablename] property"); 
    } 
    $table = $r->getStaticPropertyValue(&#39;tablename&#39;); 
    if (!$r->hasProperty(&#39;id&#39;)) { 
      throw new Exception("Class &#39;$class&#39; 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 != &#39;id&#39;) { 
        $sql = $sql . &#39;,&#39;; 
      } else { 
        continue; 
      } 
      if (is_null($val)) 
        throw new Exception($class . &#39;->&#39; . "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 &#39;no&#39;; 
    } 
    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 == &#39;id&#39;) 
        continue; 
      if ($l) 
        $sql = $sql . &#39;,&#39;; 
      if (is_string($val)) 
        $sql = $sql . "$name=&#39;$val&#39;"; 
      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); 
  } 
?>

다음은 사용 예입니다.

<?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"); 
  // 下面是一个持久对象的类的定义 
  // 每个持久对象类都必须有一个叫做$tablename静态成员,它表示数据库中存储对象的表名 
  // 类的每个成员都必须初始化,也就是必须给它一个初始值 
  // 成员变量只能为字符串或者整型,而且请定义成public的,只有public的成员变量会被映射 
  class User{ 
    public static $tablename = &#39;t_user&#39;;  // 静态变量,对象的表名,必须的 
    public $id = 0; // 对象ID,对应表中的主键,必须的,而且必须初始化为0 
     
    public $name = &#39;&#39;; // 姓名,必须初始化 
    public $age = 0; // 年龄,必须初始化 
    public $email = &#39;&#39;; // 必须初始化  
  } 
   
  // 注意:下面的语句一定要在定义好类之后运行一下,修改了类也需要运行一下,它完成创建表的工作 
  // SinORM_ResetORM(&#39;User&#39;); // 这一句只是一开始执行一次,执行之后就会自动在数据库中建立User对应的表 
   
  $user1 = new User();  // 创建一个对象 
  $user1->name = &#39;TRB&#39;; 
  $user1->age = 22; 
  $user1->email = &#39;trbbadboy@qq.com&#39;; 
  SinORM_SaveObject($user1); // 把对象保存到数据库中 
   
  // 保存之后会自动给id的 
  $id = $user1->id; 
  echo $id . &#39;<br/>&#39;; 
    
  $user2 = SinORM_GetObject(&#39;User&#39;, $id); // 通过ID从数据库创建一个对象 
  echo $user2->name . &#39;<br/>&#39;; 
   
  $user1->name = &#39;trb&#39;; // 改变一下 
  SinORM_Update($user1); // 更新到数据库 
   
  $user3 = SinORM_GetObject(&#39;User&#39;, $id); // 重新读出 
  echo $user3->name . &#39;<br/>&#39;; 
?>

요약: 위는 이 기사의 전체 내용입니다. 모든 학습에 도움이 되기를 바랍니다. .

관련 권장 사항:

PHP 프로세스 제어 및 수학적 연산 방법

PHP 변수 및 날짜 처리 사례

PHP 가비지 수집 메커니즘 관련 문제

위 내용은 PHP에서 지속성 레이어를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.