In this article, you’ll learn how to use Phalcon’s Event Manager to build an Observer Pattern architecture, complete with code samples and a step-by-step explanation.
Here’s an example listener class:
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Component;
class MyListener extends Component
{
public function beforeNotify(Event $event, $source, $data)
{
echo "Before execution, source: " . get_class($source) . ", data: " . $data . "<br>";
}
public function afterNotify(Event $event, $source, $data)
{
echo "After execution, source: " . get_class($source) . ", data: " . $data . "<br>";
}
}
This class, MyListener, extends Phalcon’s base component class and defines two methods, beforeNotify and afterNotify, which are executed before and after the event is triggered.
use Phalcon\Events\Manager;
$eventsManager = new Manager();
$myListener = new MyListener();
$eventsManager->attach('notify:before', $myListener);
$eventsManager->attach('notify:after', $myListener);
In this code, we attach the MyListener instance to the events named notify:before and notify:after, allowing it to respond accordingly when those events are triggered.
Here’s how you do it:
$eventsManager->fire('notify:before', $someObject, 'Some Data');
$eventsManager->fire('notify:after', $someObject, 'Some Data');
In this example, $someObject is the source of the event, and 'Some Data' is the payload passed to the event listeners.
Before execution, source: SomeObject, data: Some Data
After execution, source: SomeObject, data: Some Data
Use this event-driven approach in your Phalcon applications to build scalable and well-structured systems.