Callbacks

Callbacks allow the programmer to hook into the life cycle of an ActiveRecord\Model object. You can control the state of your object by declaring certain methods to be called before or after methods are invoked on your object inside of ActiveRecord.

Before callbacks

If a before_* callback returns false, execution of any other callbacks after the offending callback will not be fired and the model will not be saved/deleted.

before_save: called before a model is saved
before_create: called before a NEW model is to be inserted into the database
before_update: called before an existing model has been saved
before_validation: called before running validators
before_validation_on_create: called before validation on a NEW model being inserted
before_validation_on_update: same as above except for an existing model being saved
before_destroy: called before a model has been deleted

 1 class Order extends ActiveRecord\Model {
 2   static $before_create = array('apply_tax'); # new records only
 3   static $before_save = array('upcase_state'); # new OR updated records
 4 
 5   public function apply_tax() {
 6     if ($this->state == 'VA')
 7       $tax = 0.045;
 8     elseif ($this->state == 'CA')
 9       $tax = 0.10;
10     else
11       $tax = 0.02;
12 
13     $this->tax = $this->price * $tax;
14   }
15 
16   public function upcase_state() {
17     $this->state = strtoupper($this->state);
18   }
19 }
20 
21 $attributes = array('item_name' => 'Honda Civic',
22   'price' => 7000.00, 'state' => 'va');
23 
24 $order = Order::create($attributes);
25 echo $order->tax; # => 315.00
26 echo $order->state; # => VA
27 
28 # somehow our order changed states!
29 $order->state = 'nc';
30 $order->save();
31 echo $order->state; # => NC

After callbacks

after_save: called after a model is saved
after_create: called after a NEW model has been inserted into the database
after_update: called after an existing model has been saved
after_validation: called after running validators
after_validation_on_create: called after validation on a NEW model being inserted
after_validation_on_update: same as above except for an existing model being saved
after_destroy: called after a model has been deleted

 1 class User extends ActiveRecord\Model {
 2   static $after_create = array('send_new_user_email'); # new records only
 3   static $after_destroy = array('delete_all_related_data');
 4 
 5   public function delete_all_related_data() {
 6     # delete all associated objects
 7   }
 8 
 9   public function send_new_user_email() {
10     mail($this->email, "Thanks for signing up, {$this->name}!", "The subject");
11   }
12 }
13 
14 $attributes = array('name' => 'Jax', 'email' => 'nonya@nonya.com');
15 $user = User::create($attributes);
16 # an e-mail was just sent...
17 
18 $user->delete();
19 # everything associated with this user was just deleted

Also available in: HTML TXT