Yii Framework Forum: Yii Events, why do we need intermediate method without 'on' prefix - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Yii Events, why do we need intermediate method without 'on' prefix Rate Topic: -----

#1 User is offline   @Fazliddin 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 6
  • Joined: 23-July 14

Posted 08 July 2015 - 01:48 AM

Hi, learning Yii events I did not understood existence of one useless method. All Yii and third party
extension use both beforeSave and onBeforeSave as following:

abstract class CActiveRecord extends CModel
{
   ...
   public function insert($attributes=null)
   {
       ...
       if($this->beforeSave())
       ...
   }

   protected function beforeSave()
   {
      if($this->hasEventHandler('onBeforeSave'))
      {
         $event=new CModelEvent($this);
         $this->onBeforeSave($event);
         return $event->isValid;
      }
      else
         return true;
   }

   public function onBeforeSave($event)
   {
      $this->raiseEvent('onBeforeSave',$event);
   }

}


So why do we need beforeSave here. One could write as following:

abstract class CActiveRecord extends CModel
{
   ...
   public function insert($attributes=null)
   {
       ...
       if($this->onBeforeSave())
       ...
   }

   public function onBeforeSave($event)
   {
      if($this->hasEventHandler('onBeforeSave'))
      {
         $event=new CModelEvent($this);
         $this->raiseEvent('onBeforeSave',$event);
         return $event->isValid;
      }
      else
         return true;
   }
}

0

#2 User is offline   itma 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 92
  • Joined: 16-September 13

Posted 08 July 2015 - 03:19 AM

As you may notice beforeSave() is just a wrapper for the event method to raise. It returns boolean result and its main goal is to give you a place to implement you logic if needed (in concret model of course). onBeforeSave method belongs to list methods available in Yii and you should not change the body of that method. It's about additional abstraction layer.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users