Skip to content

Basic implementation for Event Handlers in PHP.

Notifications You must be signed in to change notification settings

TomWright/Eventing

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Eventing

Build Status Total Downloads Latest Stable Version Latest Unstable Version License

Usage

You need an Event and an EventHandler.

Let's say we have an event class stored in app/eventing/event/UserWasRegistered.php.

namespace App\Eventing\Event;

class UserWasRegistered extends \TomWright\Eventing\Event\Event
{
	protected $userId;
    
    public function setUserId($userId)
    {
    	$this->userId = $userId;
    }
    
    public function getUserId()
    {
    	return $this->userId;
    }
}

Let's also assume we have an event handler class stored in app/eventing/handler/UserWasRegisteredHandler.php.

namespace App\Eventing\Handler;

class UserWasRegisteredHandler implements \TomWright\Eventing\Listener\ListenerInterface
{   
    public function handle(\TomWright\Eventing\Event\EventInterface $event)
    {
    	echo "User #{$event->getUserId()} has been registered.";
    }
}

Now we need to add an Event Handler/Listener namespace so as the EventBus knows where to look for the handlers.

$bus = \TomWright\Eventing\EventBus::getInstance();
$bus->addListenerNamespace('\\App\\Eventing\\Handler');

Now whenever we register a new user, all we have to do is the following:

$bus = \TomWright\Eventing\EventBus::getInstance();
$event = new \App\Eventing\Event\UserWasRegistered();
$event->setUserId(123);
$bus->dispatch($event);

About

Basic implementation for Event Handlers in PHP.

Resources

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages