php事件和行为,PHP 事件机制练习代码

这篇博客介绍了PHP中事件驱动编程的概念,通过一个注销事件的例子展示了如何创建事件类、监听类和事件调度器。代码示例中,`LogoutEvent`触发后,`LogoutListener`会处理并打印出告别消息。这提供了一个遵循PSR-14规范的简单事件机制的实现。
摘要由CSDN通过智能技术生成

注意:以下代码纯属练习。想要实现优良的事件机制,请参考 PSR-14 规范。

/**

* 事件类的接口

* Interface EventInterface

*/

interface EventInterface{

public function listener(): array;

}

/**

* 登出事件

* Class LogoutEvent

*/

class LogoutEvent implements EventInterface

{

/**

* @var object 保存一个触发事件的对象

*/

public $target;

public function __construct($target)

{

$this->target = $target;

}

/**

* 返回监听这个事件的类名

* @return string[]

*/

public function listener(): array

{

return [

LogoutListener::class,

];

}

}

/**

* 监听类接口

* Interface ListenerInterface

*/

interface ListenerInterface

{

public function process(EventInterface $event);

}

/**

* 监听类

* Class LogoutListener

*/

class LogoutListener implements ListenerInterface

{

/**

* 事件触发后执行的代码

* @param EventInterface $event

*/

public function process(EventInterface $event)

{

echo 'See you next time, ' . $event->target->username . PHP_EOL;

}

}

/**

* 事件调度器

* Class EventDispatch

*/

class EventDispatch{

private $event;

public function __construct(EventInterface $event){

$this->event = $event;

}

public function dispatch()

{

$listeners = $this->event->listener();

foreach ($listeners as $listener)

{

$listenerObj = new $listener();

$listenerObj->process($this->event);

}

}

}

class App {

public function logout(){

$user = new \stdClass();

$user->username = 'Lee';

$event = new LogoutEvent($user);

$eventDispatch = new EventDispatch($event);

$eventDispatch->dispatch();

}

}

$app = new App();

$app->logout();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值