Finder events are divided by two categories:
- Events before find
- Events after find
Names of these events are defined as constants in
and it is highly recommended to use this constants to [attach][at]
All events of each category work in the same way. The difference is when these are raised.
This finder actions can be divided like following:
find- executed before or after
find*methods. For example:
exists- executed before or after executing
count- executed before or after
count*methids. For example:
Before Find (Exists, Count)
$sender property of before find/count/exists events
contains new or any model passed to finder method. It does not
contain found model - as the query execusion is not performed yet.
Available before events:
beforeFind- defined as constant
beforeExists- defined as constant
beforeCount- defined as constant
Events before find can actually prevent executing query. This might be useful for access control checking or any scenario where data should not be returned for any reason.
To prevent action execution event property
$isValid must be
false. However, different event can set this value back to
To ensure that no other events will try to handle current event, set property
true. This will stop event chain and return to action execution.
To ensure that currently handled event will be considered
as stopping action, ensure that
$handled is set.
Other use cases
Events can be used also on other scenarios, including but not limited to:
- Modifying criteria to add multi-tenant scope
- Access control checking by adding extra criteria
- Logging queries
After Find (Exists, Count)
The after find, exists, count events can be used to do something with found model.
- Change some of the object properties
- Log views count of concrete document
As action was already performed, the
$isValid property is irrelevant.
$handled property if set to
true while handling event, will prevent
other event handlers to be executed. Please note however, that events order is not guaranteed
so do not rely on this behavior.
$sender property in events kind afterFind contain actually found model.
In case of afterExists and afterCount events, the property
$sender contains model passed to
Finder instance - as in this methods model
is not even retrieved from database.
The after find event will be triggered for every model in found set. That is, it can fire many, many times.
Available after events:
afterFind- defined as constant
afterExists- defined as constant
afterCount- defined as constant