-
Notifications
You must be signed in to change notification settings - Fork 5
model events
Various events are broadcasted by all models. You can listen to these events and act upon them from behaviors and validators but also from the model itself. A callback method need not return a value. If a callback method wishes to alter any of its parameters, it should edit them in place, by reference. Remember to grab the reference as follows:
<?php
public function beforeInsert(&$args) {
$data = &$args[1];
$data['foo'] = 'bar';
}
?>
Note that callback methods do not need to return values. If fact; if they were to return values, those values would not be used by the model. An exception to this rule, in a way, is the beforeFetch() method. This method receives a third parameter by reference, much like the $matches parameter to preg_match(). After broadcasting the event, the model will check to see if $results is populated. If so, no live results are fetched, but $results is used.
This is done so that behaviors may decide to take an alternative route in fetching results. For instance the core behavior Garp_Model_Behavior_Cachable fetches data from the cache instead of the database when valid cached data is available.
The following is a list of all events and the parameters that are sent with them. Note that every callback method receives one argument: an array containing the parameters as listed below.
- 0: the model object
- 1: the Zend_Db_Select object
- 2: &$results
That third parameter is a special one: you may populate it with anything other than the int -1 and this will automatically be used as the result of the fetch call. The most notable use for this is in the Cachable behavior, which intercepts the fetch call and populates $results with cached results.
- 0: the model object
- 1: result of the query
- 0: the model object
- 1: the new record's data (array)
- 0: the model object
- 1: the new record's data (array)
- 2: the primary key associated with the new record (last_insert_id)
- 0: the model object
- 1: the new data (array)
- 2: he WHERE clause (string)
- 0: the model object
- 1: result of the update call
- 2: the new data (array)
- 3: the WHERE clause (string)
- 0: the model object
- 1: the WHERE clause (string)
- 0: the model object
- 1: result of the delete call
- 2: the WHERE clause
- 0: the model object
- 1: relationship alias
- 2: bind options
- 0: the model object
- 1: relationship alias
Want to listen to the above events? Register your observer with the model. A good place to do so is in the init method of the model:
<?php
public function init() {
$this->registerObserver(
new App_My_Observer()
);
parent::init();
}
?>
Simply implement a method with a name matching the event that receives one argument (an array) and you're good to go.