Events can be triggered by any object you'd like. Below is some sample code showing how this might be accomplished. The example assumes the existance of a User
class.
Generally when implementing custom events, you'll have at least 3 objects:
1) An event manager (an instance of Phalcon\Events\ManagerInterface
).
2) An event "emitter" (often an instance of Phalcon\Events\EventsAwareInterface
).
3) One or more event "listeners", which have methods bound to particular events.
In your case, the emitter might look something like this:
class UserController implements Phalcon\Events\EventsAwareInterface
{
protected $_eventsManager;
public function setEventsManager(Phalcon\Events\ManagerInterface $manager)
{
$this->_eventsManager = $manager;
}
public function getEventsManager()
{
return $this->_eventsManager;
}
public function register(User $user)
{
// do registration...
$this->getEventsManager()->fire("users:registerUser", $this, $user);
}
public function updateProfile(User $user)
{
// do update...
$this->getEventsManager()->fire("users:updateUser", $this, $user);
}
public function delete(User $user)
{
// do delete...
$this->getEventsManager()->fire("users:deleteUser", $this, $user);
}
}
Your listener might look something like this:
class UserControllerListener
{
public function registerUser(Phalcon\Events\Event $event, UserController $cntrl, User $user)
{
// do stuff...
}
}
Put it all together:
// Create the event emitter.
$cntrl = new UserController();
// Set the event manager.
$cntrl->setEventsManager(new Phalcon\Events\Manager());
// Create the event listener.
$listener = new UserControllerListener();
// Attach the listener to "users" events.
$cntrl->getEventsManager()->attach("users", $listener);
In this case, if a method with the same name as the event exists, it will be invoked when the event is triggered (e.g. when the users:registerUser
event is triggered, the UserControllerListener::registerUser()
method is invoked).
An alternative listener implementation might look like this:
class UserControllerListener
{
public function onUserRegistration(Phalcon\Events\Event $event, UserController $cntrl, User $user)
{
// do stuff...
}
}
In this case, you'll need to directly attach the event to the callback method:
// Create the event emitter.
$cntrl = new UserController();
// Set the event manager.
$cntrl->setEventsManager(new Phalcon\Events\Manager());
// Create the event listener.
$listener = new UserControllerListener();
// Attach the listener to "users:registerUser" events.
$cntrl->getEventsManager()->attach("users:registerUser", [$listener, "onUserRegistration"]);