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

PHP 註冊器模式實現:單例容器與依賴管理實戰

     編輯:PHP 綜合知識

註冊器模式(Registry Pattern)提供全域存取點,管理共享物件實例,是依賴注入容器的簡化形態。本文展示基於 ArrayObject 的線程安全實現。

核心類設計

class Registry extends ArrayObject {
    private static $_instance = null;

    // 單例模式
    public static function getInstance() {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    // 靜態代理方法
    public static function set($name, $value) {
        self::getInstance()->offsetSet($name, $value);
    }
    public static function get($name) {
        $ins = self::getInstance();
        return $ins->offsetExists($name) ? $ins->offsetGet($name) : null;
    }
    public static function has($name) {
        return self::getInstance()->offsetExists($name);
    }
    public static function remove($name) {
        self::getInstance()->offsetUnset($name);
    }
}

使用示例

// 註冊服務物件
$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
Registry::set('db', $db);

$cache = new Redis();
$cache->connect('127.0.0.1', 6379);
Registry::set('cache', $cache);

// 任意處獲取
$db = Registry::get('db');
$stmt = $db->query('SELECT * FROM users');
$user = $stmt->fetch();

// 檢查是否註冊
if (Registry::has('logger')) {
    Registry::get('logger')->info('Request processed');
}

進階擴展方向

  • 延遲載入:結合 Closure 實現惰性實例化
  • 命名空間隔離:鍵名採用 service.db、config.app 格式
  • 唯讀鎖定:凍結關鍵服務防止覆寫
  • PSR-11 兼容:實現 ContainerInterface 標準化

適用場景與局限

優點缺點
全域存取便利隱式依賴難追蹤
單例保證資源復用單元測試需 Mock 容器
實現簡單輕量非嚴格 DI 容器替代品

最佳實踐:僅用於基礎設施服務(DB、Cache、Config、Logger),業務邏輯物件優先採用建構子注入。現代框架(Laravel、Symfony)已內建完整 DI 容器,舊專案遷移時可漸進式替換。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved