note 103201 deleted from functions.anonymous by danbrown

From: Date: Thu, 31 Mar 2011 13:47:11 +0000
Subject: note 103201 deleted from functions.anonymous by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-178374@lists.php.net to get a copy of this message
Note Submitter: fabio dot bat dot silva at gmail dot com ---- This library implements the Observer pattern using php 5.3 https://github.com/FabioBatSilva/events/ Package : IEventDispatcher : The IEventDispatcher interface defines methods for all dispatchers. EventDispatcher : The EventDispatcher class is the base class for all runtime classes that dispatch events. Event : The Event class is used as the base class for the creation of Event objects. Loading : You can load the library using any autoload. Ex:Zend_AutoLoad For manual load Here's a nice sample: set_include_path('/my/library' . PATH_SEPARATOR . get_include_path()); require_once 'Events/Event.php'; use Events\Event; Dispatching Events : To trigger events you can extend the EventDispatcher class and use method dispatchEvent($event) The parameter of this method is the Event that will trigger use Events\Event, Events\EventDispatcher; class MyObject extends EventDispatcher { private $name; public function setName($name) { $this->dispatchEvent(new Event(Event::CHANGE)); $this->name = $name; } } Listening for Events : When you need listen events you must use the method addEventListener($type,$listener). First parameter is a string that identifies the type of event The second parameter is a Closure / Function that will be called when the event trigger $object = new MyObject(); $object->addEventListener(Event::CHANGE, function($event){ echo 'My Object Has Changed'; }); $object->setName('New Name'); Custom Events : You can create custom events as part of components. Custom events let you add functionality to your custom components to respond to interactions. use Events\Event; class MyEvent extends Event { const CHANGE_NAME = 'changeName'; public $oldName; public $newName; public function __construct($type, $oldName = null, $newName = null) { parent::__construct($type); $this->oldName = $oldName; $this->newName = $newName; } } Then dispatch custom event. public function setName($name) { $event = new MyEvent(MyEvent::CHANGE_NAME, $this->name, $name); $this->dispatchEvent($event); $this->name = $name; } And capture the values at listener $object->addEventListener(MyEvent::CHANGE_NAME, function($event){ echo "My Object Has Changed"; echo "OLD : " + $event->oldName; echo "NEW : " + $event->newName; });

« previous php.notes (#178374) next »