PHP 事件机制练习代码

注意:以下代码纯属练习。想要实现优良的事件机制,请参考 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();

猜你喜欢

转载自blog.csdn.net/weixin_40369062/article/details/107932878