在非 laravel 專案中使用 laravel 的特性 11: Event && Listener

ZouZhipeng發表於2021-03-10

安裝所需的擴充套件包

composer require illuminate/events

新建 event 檔案 src/Events/UserHasRegisteredEvent.php

<?php

namespace App\Events;

class UserHasRegisteredEvent
{
    protected $username;

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

    public function getUsername()
    {
        return $this->username;
    }
}

新建 listener 檔案 src/Listeners/SendWelcomingEmail.php

<?php

namespace App\Listeners;

use App\Events\UserHasRegisteredEvent;

class SendWelcomingEmail
{
    public function handle(UserHasRegisteredEvent $event)
    {
        echo $event->getUsername() . ', welcome to my world!';
    }
}

專案根目錄新建入口 index/event.php

<?php

include __DIR__ . '/../vendor/autoload.php';

use App\Events\UserHasRegisteredEvent;
use App\Listeners\SendWelcomingEmail;

$dispatcher = new \Illuminate\Events\Dispatcher();

// Defining the listeners
$dispatcher->listen([UserHasRegisteredEvent::class], SendWelcomingEmail::class);

// Firing the event
$dispatcher->dispatch(new UserHasRegisteredEvent('Joey'));

命令列開啟服務 php -S localhost:8000 並訪問 http://localhost:8000/index/event.php 即可。

由於沒有統一的觀察者繫結入口 (laravel 中的 EventServiceProvider),所以都需要在使用時進行手動繫結,待優化。

參考 致謝

  1. mattstauffer/Torch
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章