Esempio n. 1
0
 public function save()
 {
     if (!$this->beforeSave()) {
         return false;
     }
     # begin transaction
     $transactionKey = md5(microtime() . rand(0, 10)) . get_class($this);
     try {
         \Uc::app()->db->startTransaction($transactionKey);
         if (!empty($this->columnChanged) or $this->stored == false) {
             $table = $this->table;
             # insert or update
             if ($this->stored) {
                 # do Update of entity
                 $pk = $this->pk();
                 $fields = array_intersect_key($this->data, $this->columnChanged);
                 $result = $this->table->update($fields, $pk);
             } else {
                 # do Insert of entity
                 $result = $this->table->insert($this->data);
                 if ($result != false) {
                     # set primary key for entity
                     /*
                      * @todo update full data for Entity.
                      * For example we have fields id, name, title, date
                      * date is set automatically with database engine
                      * if we make insert in future we want to get date
                      * for this entity.
                      * So we need to set date for this model
                      * Look up to zend db
                      */
                     # Primary key can be set from modules.
                     $pk = $table->pk();
                     if (empty($this->{$pk})) {
                         $this->{$pk} = $result;
                         # last insert id
                     }
                 }
             }
             if ($result) {
                 # make entity new state
                 $this->stored = true;
                 $this->columnChanged = array();
             } else {
                 throw new \Exception('Can not save entity ' . get_class($this));
             }
         }
         # end transaction
         // @todo make rollback
         \Uc::app()->db->endTransaction($transactionKey);
     } catch (\Exception $exc) {
         echo $exc->getMessage() . "\n";
         echo $exc->getTraceAsString();
     }
     $this->afterSave();
     return true;
 }