Advertisement
lignite0

ORM piece of mind 3

Aug 31st, 2015
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.18 KB | None | 0 0
  1. <?php
  2.  
  3. class ActiveTable
  4. {
  5.     public $name = 'noname';
  6.    
  7.     public function __construct($tableName)
  8.     {
  9.         $this->name = $tableName;
  10.     }
  11. }
  12.  
  13. class MemberTable extends ActiveTable
  14. {
  15.    
  16. }
  17.  
  18. class ActiveRecord
  19. {    
  20.     public function __construct()
  21.     {
  22.         echo "<pre>"; print_r($this); echo "</pre>";
  23.     }
  24.    
  25.     public function insertIntoTable(ActiveTable $table)
  26.     {
  27.         $fields = array_map(
  28.             function($element){
  29.                 if (is_string($element))
  30.                     return "'$element'";
  31.                 if (is_int($element))
  32.                     return $element;
  33.                 if (is_null($element))
  34.                     return "NULL";
  35.                 if (is_float($element))
  36.                     return "'$element'";
  37.             },
  38.             $this->getAsArray()
  39.         );
  40.         $r = 'INSERT INTO '.$table->name.' ('.implode(', ', array_keys($fields)).') VALUES ('.implode(', ', $fields).')';
  41.         echo "<pre>"; print_r($r); echo "</pre>";
  42.     }
  43.    
  44.     public static function createFromArray($fields = array())
  45.     {
  46.         $instance = new static();
  47.         foreach ($fields as $fieldName => $fieldValue) {
  48.             $instance->$fieldName = $fieldValue;
  49.         }
  50.         return $instance;
  51.     }
  52.    
  53.     public function getAsArray()
  54.     {
  55.         $recordValues = array();
  56.         foreach ($this as $fieldName => $fieldValue) {            
  57.             $recordValues[$fieldName] = $fieldValue;
  58.         }
  59.         return $recordValues;
  60.     }
  61. }
  62.  
  63. class Member extends ActiveRecord
  64. {
  65.     public $memberID = null;
  66.     public $groupID = null;
  67.     public $username = '';
  68.    
  69.     public function __construct()
  70.     {
  71.         parent::__construct();
  72.     }
  73. }
  74.  
  75. $table = new ActiveTable('prefix__members_lang_pl');
  76.  
  77. $ar = new ActiveRecord();
  78. $ar->userID = 5;
  79. $ar->insertIntoTable($table);
  80.  
  81. $ar = ActiveRecord::createFromArray(array(
  82.     'username' => 'root',
  83.     'password' => 'd033e22ae348aeb5660fc2140aec35850c4da997',
  84. ));
  85. $ar->insertIntoTable($table);
  86.  
  87.  
  88. $mem = new Member();
  89. $mem->insertIntoTable($table);
  90.  
  91. $mem = new Member();
  92. unset($mem->groupID);
  93. $mem->insertIntoTable($table);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement