首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實作事件機制(Observer 模式):利用 debug_backtrace 限制觸發者

     編輯:PHP 綜合知識

設計目標

PHP 內建無事件機制,需自行實作 Observer 模式。關鍵需求:監聽者可由任何物件註冊,但事件只能由直接包含該事件物件的持有者觸發。

核心實作:Event 類別

<?php
class Event {
    private $callbacks = array();
    private $holder;

    function __construct() {
        $bt = debug_backtrace();
        if (count($bt) < 2) {
            $this->holder = null;
            return;
        }
        // 取得實例化 Event 的物件(即持有者)
        $this->holder = &$bt[1]['object'];
    }

    function attach() {
        $args = func_get_args();
        switch (count($args)) {
            case 1:
                if (is_callable($args[0])) {
                    $this->callbacks[] = $args[0];
                }
                break;
            case 2:
                if (is_object($args[0]) && is_string($args[1])) {
                    $this->callbacks[] = array(&$args[0], $args[1]);
                }
                break;
        }
    }

    function notify() {
        $bt = debug_backtrace();
        // 驗證呼叫者是否為持有者
        if ($this->holder && ((count($bt) >= 2 && $bt[count($bt)-1]['object'] !== $this->holder) || count($bt) < 2)) {
            throw new Exception('Notify can only be called in holder');
        }
        foreach ($this->callbacks as $callback) {
            $args = func_get_args();
            call_user_func_array($callback, $args);
        }
    }
}

關鍵技術點解析

  1. debug_backtrace():取得呼叫堆疊,$bt[1]['object'] 即為實例化 Event 的物件(持有者)
  2. attach() 多型支援:接受 Closure 或 [$object, 'methodName'] 陣列
  3. notify() 權限檢查:比對呼叫堆疊最底層物件是否為 holder,防止外部任意觸發

使用範例

class User {
    public $onLogin;
    function __construct() {
        $this->onLogin = new Event();
    }
    function login($name) {
        echo "$name logged in\n";
        $this->onLogin->notify($name); // 僅 User 物件可觸發
    }
}

$user = new User();
$user->onLogin->attach(function($name) { echo "Send welcome email to $name\n"; });
$user->onLogin->attach($user, 'sendNotification'); // 假設 User 有 sendNotification 方法

$user->login('Alice'); // 正常觸發
// $user->onLogin->notify('Bob'); // 若在外部呼叫會拋出 Exception

適用場景

  • 框架核心事件系統(如 Laravel 的 Event Dispatcher 簡化版)
  • 插件架構的鉤子機制
  • 領域驅動設計中的領域事件
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved