Difference between #3 and #4 of
Extending an ActiveRecord model

Revision #4 has been created by Bogsey on Feb 19, 2013, 4:23:32 PM with the memo:

Changed override methods to beforeSave() and instantiate
« previous (#3)

Changes

Title unchanged

Extending an ActiveRecord model

Category unchanged

How-tos

Yii version unchanged

Tags unchanged

active record, CActiveRecord, extending

Content changed

[...]
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/**
 * Overrides the ActiveRecord save to insert the extra parameters
 
   * This class has into JSON text and save it in the data base
Saves meta data in the params attribute
 
    * @return boolean
  */ public function save($runValidation = true, $attributes = nullbeforeSave() {
$this->name = get_class($this);
$vars = get_object_vars($this);
[...]
}
/**
 * Overrides the ActiveRecord function to read the extra params andCreates the correct class type and populates the meta data   * create a new class based on the data and return the sub class@param array $attributes
 
    * @return CActiveRecord
  */   public function findByPk($pk, $condition = '', $params = array()) {
 
     $result = parent::findByPk($pk, $condition, $params);
 
     if ($result !== null) {
 
         $extendedV
stantiate($attributes) {
 
       $v
ars = json_decode($result->attributes['params'], true);    $type = $extendedVvars['name'];   $subClass = new $type;   foreach ($extendedVvars as $key => $var) {    if (property_exists($subClass, $key)) {    $subClass->$key = $var;   }    }   $subClass->attributes = $result->attributes;
 
         return $subClass;
 
     }
 
     return false
return $subClass;
}
}
```
Now all we need to do is change the subclass definitions to extend from this new class
[...]
2 3
7 followers
Viewed: 19 287 times
Version: 1.1
Category: How-tos
Written by: Bogsey
Last updated by: Bogsey
Created on: Feb 18, 2013
Last updated: 5 years ago
Update Article

Revisions

View all history