PHP code example of constanze-standard / event-dispatcher
1. Go to this page and download the library: Download constanze-standard/event-dispatcher library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
constanze-standard / event-dispatcher example snippets
use ConstanzeStandard\EventDispatcher\Event;
$event = new Event();
echo $event->getName(); // \ConstanzeStandard\EventDispatcher\Event
use ConstanzeStandard\EventDispatcher\Event;
class CustomEvent extends Event
{
private $id;
private $data;
public function __construct($id, $data)
{
$this->id = $id;
$this->data = $data;
}
public function getName()
{
return $id;
}
}
$event = new CustomEvent('user.create', ['id' => 1, 'name' => 'Alex']);
use ConstanzeStandard\EventDispatcher\Event;
class CustomEvent extends Event implements \Serializable
{
...
public function serialize()
{
return serialize([
'name' => $this->name,
'data' => $this->data
]);
}
public function unserialize($serialized)
{
$array = unserialize($serialized);
$this->name = $array['name'];
$this->data = $array['data'];
}
}
$event = new CustomEvent('user.create', ['id' => 1, 'name' => 'Alex']);
$decompEvent = unserialize(serialize($event));
use ConstanzeStandard\EventDispatcher\Interfaces\EventInterface;
// 可调用对象
function onSomeEvent(EventInterface $event) {
echo $event->getName();
return $event;
}
class Listener
{
// 普通的类方法
public function onSomeEvent(EventInterface $event)
{
echo $event->getName();
return $event;
}
}
use ConstanzeStandard\EventDispatcher\Interfaces\EventInterface;
function onSomeEvent(EventInterface $event) {
return $event->withPropagationStopped();
}
use ConstanzeStandard\EventDispatcher\ListenerProvider;
$listenerProvider = new ListenerProvider();
$listenerProvider->addListener('user.create', onSomeEvent::class, 2);
$listenerProvider->addListener('user.create', [new Listener(), 'onSomeEvent'], 10);
use ConstanzeStandard\EventDispatcher\EventDispatcher;
use Psr\EventDispatcher\ListenerProviderInterface;
/** @var ListenerProviderInterface $listenerProvider */
$dispatcher = new EventDispatcher($listenerProvider);
$dispatcher->dispatch($event);
use ConstanzeStandard\EventDispatcher\Interfaces\EventInterface;
use ConstanzeStandard\EventDispatcher\Interfaces\SubscriberInterface;
class UserSubscriber implements SubscriberInterface
{
public function subscribe(Closure $subscriber)
{
$subscriber(
'user.signup',
'onSignup',
['onCreate', 1]
);
}
public function onSignup(EventInterface $event)
{
...
return $event;
}
public function onCreate(EventInterface $event)
{
...
return $event;
}
}
$listenerProvider->addSubscriber(new UserSubscriber());
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.