$modelOne = Expence::model()->findByPk(10); $modelTwo = Expence::model()->findByPk(10); var_dump($modelOne === $modelTwo); // false
$modelOne->someField = "Data"; $modelOne->save(); /// ...- ... echo $modelTwo->someField; // $modelTwo->save(); //
<?php /** * Singleton class to manipulate instances of models (eg CActiveRecord). * * @author Yuriy Ratanov <organium@gmail.com> */ class ObjectWatcher { /** * Current instance of ObjectWatcher * @var ObjectWatcher */ private static $_instance; /** * Array of objects to work with. * @var array */ private $objects = array(); /** * Geting instance of ObjectWatcher. * @return ObjectWatcher */ static function getInstance(){ if(!isset(self::$_instance)){ self::$_instance = new ObjectWatcher; } return self::$_instance; } /** * Getting instance of the object existing in the current application. * @param string $className * @param int $id * @return mixed null or object of the class $className with an id = $id if it exists. */ static function getRecord($className, $id) { $inst = self::getInstance(); $key = "$className.$id"; if(isset($inst->objects[$key])){ return $inst->objects[$key]; } return null; } /** * Adding object to ObjectWatcher registry. * @param $obj * @param int $id */ static function addRecord($obj, $id) { $inst = self::getInstance(); $inst->objects[$inst->getKey($obj, $id)] = $obj; } function getKey($obj, $id){ return get_class($obj).'.'.$id; } }
<?php class Expence extends CActiveRecord { //...- protected function instantiate($attributes) { if(($record = ObjectWatcher::getRecord(get_class($this), $attributes['id'])) != false){ // , $model = $record; }else{// $model = parent::instantiate($attributes); ObjectWatcher::addRecord($model, $attributes['id']);// } return $model; } //...- }
$modelOne = Expence::model()->findByPk(10); $modelTwo = Expence::model()->findByPk(10); var_dump($modelOne === $modelTwo); // true
Source: https://habr.com/ru/post/143497/
All Articles