萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 單例模式實作指南:資源共享、狀態管理與現代寫法

單例模式確保類別在全域只有一個實例,並提供全域存取點。在 PHP 中常用於資料庫連線、配置管理、日誌記錄器、快取驅動等「重資源、共享狀態」場景。本文從經典寫法到現代 PHP 8+ 最佳實踐,完整解析單例模式實作細節、常見誤區與替代方案。

經典單例寫法 (PHP 5 風格)

<?php
class Database {
    // 1. 私有靜態實例容器
    private static ?self $instance = null;
    
    // 2. 私有建構子 (防外部 new)
    private function __construct(
        private string $host,
        private string $dbname,
        private string $user,
        private string $pass
    ) {
        // 實際連線邏輯...
        $this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->user, $this->pass);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    
    // 3. 禁止複製
    private function __clone() {}
    public function __wakeup() { throw new Exception("不能反序列化單例"); }
    
    // 4. 靜態工廠方法
    public static function getInstance(string $host, string $dbname, string $user, string $pass): self {
        if (self::$instance === null) {
            self::$instance = new self($host, $dbname, $user, $pass);
        }
        return self::$instance;
    }
    
    // 業務方法
    public function query(string $sql): PDOStatement { /* ... */ }
}

// 使用
$db = Database::getInstance('localhost', 'mydb', 'user', 'pass');
$stmt = $db->query('SELECT * FROM users');

現代 PHP 8.1+ 單例最佳實踐

<?php
final class Config {
    // 1. 唯讀屬性 + 建構子提升
    public function __construct(
        public readonly string $appName,
        public readonly string $env,
        public readonly array $db,
        public readonly array $cache,
    ) {}
    
    // 2. 靜態工廠 (支援參數化單例:不同參數不同實例)
    private static array $instances = [];
    
    public static function getInstance(string $env = 'production'): self {
        if (!isset(self::$instances[$env])) {
            $configFile = __DIR__ . "/config/{$env}.php";
            if (!is_file($configFile)) {
                throw new RuntimeException("配置檔不存在:$configFile");
            }
            $data = require $configFile;
            self::$instances[$env] = new self(
                $data['app_name'] ?? 'MyApp',
                $env,
                $data['db'] ?? [],
                $data['cache'] ?? [],
            );
        }
        return self::$instances[$env];
    }
    
    // 3. 禁止複製/序列化
    private function __clone() {}
    public function __wakeup() { throw new Exception("不可反序列化"); }
    
    // 4. 便利存取器
    public function db(string $key, mixed $default = null): mixed {
        return $this->db[$key] ?? $default;
    }
}

// 使用
$prodConfig = Config::getInstance('production');
$testConfig = Config::getInstance('testing'); // 不同參數 = 不同實例

echo $prodConfig->appName; // MyApp
$dbHost = $prodConfig->db('host', '127.0.0.1');

單例模式適用場景 vs 反模式

✅ 適合單例❌ 不適合單例
資料庫連線池/連線管理器一般業務邏輯服務 (UserService, OrderService)
配置管理器 (唯讀)實體/模型類別 (User, Product)
日誌記錄器控制器
快取驅動 (Redis/Memcached 連線)請求上下文相關物件
事件分發器/總線需依賴請求資料的服務
檔案系統抽象層狀態頻繁變更的物件

單例的核心缺點與緩解策略

  1. 全域狀態難測試:單元測試間相互干擾。
    • 緩解:提供 resetInstance() (僅測試環境)、使用依賴注入容器管理生命週期而非硬編碼 ::getInstance()。
  2. 隱性依賴:類別內部直接呼叫 Logger::getInstance(),外部無法看出依賴關係。
    • 緩解:建構子注入介面 LoggerInterface $logger,容器綁定單例實現。
  3. 併發安全:PHP 單執行緒請求模型下無競態,但 Swoole/RoadRunner 等常駐模式需加鎖。
    • 緩解:static $instance; static $lock = false; ... if (!$lock) { $lock=true; $instance=new self; $lock=false; } 或使用 swoole_lock。
  4. 記憶體洩漏風險:長時間運行進程中單例持有大量資料。
    • 緩解:實作 clear() 釋放內部資源,定期重置。
  5. 依賴注入容器 (DIC) 管理單例:現代標準做法

    <?php
    // PSR-11 容器介面範例
    interface ContainerInterface {
        public function get(string $id): mixed;
        public function has(string $id): bool;
    }
    
    class Container implements ContainerInterface {
        private array $definitions = [];
        private array $instances = [];
        
        public function singleton(string $id, callable $factory): void {
            $this->definitions[$id] = ['factory' => $factory, 'shared' => true];
        }
        
        public function get(string $id): mixed {
            if (!isset($this->definitions[$id])) {
                throw new NotFoundException($id);
            }
            $def = $this->definitions[$id];
            if ($def['shared'] && isset($this->instances[$id])) {
                return $this->instances[$id];
            }
            $instance = $def['factory']($this);
            if ($def['shared']) $this->instances[$id] = $instance;
            return $instance;
        }
    }
    
    // 註冊
    $container = new Container();
    $container->singleton('db', fn($c) => new Database(
        $_ENV['DB_HOST'], $_ENV['DB_NAME'], $_ENV['DB_USER'], $_ENV['DB_PASS']
    ));
    $container->singleton('logger', fn($c) => new FileLogger('/var/log/app.log'));
    $container->singleton('cache', fn($c) => new RedisCache($c->get('config')->cache));
    
    // 使用 (控制器/服務透過建構子注入)
    class UserController {
        public function __construct(
            private Database $db,
            private LoggerInterface $logger,
            private CacheInterface $cache
        ) {}
    }
    
    // 容器自動解析依賴
    $controller = $container->get(UserController::class);
    

    實戰案例:資料庫連線單例 (PDO 封裝)

    <?php
    final class PdoConnection {
        private static ?PDO $pdo = null;
        
        private function __construct() {}
        
        public static function getInstance(array $config): PDO {
            if (self::$pdo === null) {
                $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
                self::$pdo = new PDO($dsn, $config['user'], $config['pass'], [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                    PDO::ATTR_PERSISTENT => $config['persistent'] ?? false,
                ]);
            }
            return self::$pdo;
        }
        
        public static function reset(): void { // 僅測試用
            self::$pdo = null;
        }
    }
    
    // 使用
    $db = PdoConnection::getInstance([
        'host' => '127.0.0.1',
        'dbname' => 'myapp',
        'user' => 'app_user',
        'pass' => 'secret',
        'charset' => 'utf8mb4',
    ]);
    

    單例 vs 靜態類別

    <?php
    // 靜態類別:無狀態、純工具函數集合
    final class StringUtils {
        private function __construct() {} // 防實例化
        
        public static function slug(string $str): string {
            return strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $str), '-'));
        }
    }
    
    // 單例:有狀態、資源持有、需延遲初始化
    final class Database { /* ... */ }
    

    判斷標準:是否需要「保持狀態」或「持有昂貴資源」?是→單例;否→靜態類別/函數集合。

    總結

    • 單例模式核心:private __construct + static $instance + static getInstance()。
    • 現代 PHP:final 類別、readonly 屬性、建構子提升、型別宣告、參數化單例。
    • 首選依賴注入容器管理單例生命週期,而非硬編碼 ::getInstance(),提升可測試性與解耦合。
    • 理解適用邊界:資源管理器✅,業務服務❌。

    單例模式是雙面刃,用得好是資源管理利器,用不好變成全域變數噩夢。掌握現代實作與 DI 容器整合,讓單例在你的架構中發揮最大價值!

copyright © 萬盛學電腦網 all rights reserved