Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Creating an event simply sets a callback to be invoked if and only if during the execution of the current program such an event is triggered. This is useful if you require notification of certain action actions throughout your applicationsapplication.

Registering an Event

Registering an events event will allow your callback to be notified when such an event is triggered. Any controller or model that inherits from AppController or AppModel will already have access to the event handler and can immediately begin registering events.

...

Note
titleAn event can be registered more than once

If you register the same event with the same callback more than once that callback will be executed multiple times each time the event is triggered.

Triggering an Event

Triggering an event invokes all callbacks that have been registered for that event. To trigger the "EventName" event invoke the Events::trigger() method and pass in any parameters that you want each of the callbacks to receive.

Code Block
languagephp
titleSomewhere in your code
$this->Events->trigger("EventName", array("square", "pink"));

Here's a complete example that will output "square pink".

Code Block
languagephp
title/app/controllers/my_controller.php
firstline1
linenumberstrue
<?php
class MyController extends AppController {

    public function index() {
        $this->Events->register("EventName", array($this, "callbackMethod"));
        $this->Events->trigger("EventName", array("square", "pink"));
        return false; // don't render a view
    }

    public function callbackMethod($shape, $color) {
        echo $shape . " " . $color;
    }
}
?>