PHP code example of tinywan / event

1. Go to this page and download the library: Download tinywan/event 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/ */

    

tinywan / event example snippets


namespace extend;

use Symfony\Contracts\EventDispatcher\Event;

class LogErrorWriteEvent extends Event
{
    const NAME = 'log.error.write';  // 事件名,事件的唯一标识

    public $log;

    public function __construct(array $log)
    {
        $this->log = $log;
    }

    public function handle()
    {
        return $this->log;
    }
}

return [
    // 事件监听
    'listener'    => [
        \extend\LogErrorWriteEvent::NAME => \extend\LogErrorWriteEvent::class,
        \extend\DingTalkEvent::NAME => \extend\DingTalkEvent::class,
    ],
];

namespace extend;


use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\Event;

class LoggerSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        // 监听的不同事件,当事件触发时,会调用 onResponse 方法
        return [
            \extend\LogErrorWriteEvent::NAME => 'onResponse',
            \extend\DingTalkEvent::NAME => 'onResponse',
        ];
    }

    /**
     * @desc: 触发事件
     * @param Event $event
     */
    public function onResponse(Event $event)
    {
        // 一些具体的业务逻辑
        var_dump($event->handle());
    }
}

return [
    // 事件订阅
    'subscriber' => [
         \extend\LoggerSubscriber::class
    ],
];

$error = [
    'errorMessage' => '错误消息',
    'errorCode' => 500
];
Tinywan\Event::trigger(new \extend\LogErrorWriteEvent($error), \extend\LogErrorWriteEvent::NAME);

$error = [
    'errorMessage' => '错误消息',
    'errorCode' => 500
];
event(new \extend\LogErrorWriteEvent($error), \extend\LogErrorWriteEvent::NAME);