創建型模式中,單例 確保類全局僅有一個實例,多例 則按鍵管理多個單例。本文深入剖析實現細節、線程安全、反序列化攻擊防護、依賴注入容器集成,並給出生產級代碼骨架。
<?php
class SingletonClassic
{
private static ?self $instance = null;
private function __construct() {}
private function __clone() {}
public function __wakeup() { throw new \Exception('不能反序列化單例'); }
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function doSomething(): void { echo "Singleton working\n"; }
}
// 使用
$obj1 = SingletonClassic::getInstance();
$obj2 = SingletonClassic::getInstance();
var_dump($obj1 === $obj2); // true
?>
<?php
class SingletonStaticLocal
{
private function __construct() {}
private function __clone() {}
public function __wakeup() { throw new \Exception('不能反序列化單例'); }
public static function getInstance(): self
{
static $instance = null; // 函數級靜態變量,首次調用初始化
if ($instance === null) {
$instance = new self();
}
return $instance;
}
}
?>
<?php
interface LoggerInterface { public function log(string $msg): void; }
class DatabaseLogger implements LoggerInterface
{
// 單例特性由容器管理,類本身不強制單例
public function __construct(private PDO $pdo) {}
public function log(string $msg): void { /* ... */ }
}
// 容器配置(如 PHP-DI, Symfony DI, Laravel Container)
$container->set(LoggerInterface::class, \DI\object(DatabaseLogger::class)->scope(\DI\Scope::SINGLETON));
// 使用時由容器注入,業務代碼無感知單例
class OrderService
{
public function __construct(private LoggerInterface $logger) {}
public function placeOrder(): void { $this->logger->log('Order placed'); }
}
?>
現代最佳實踐:**類本身不實現單例**,而是由 **DI 容器管理生命週期**(Singleton Scope)。這樣:
適用場景:數據庫連接池(不同配置)、多租戶配置、不同緩存節點客戶端、不同 API 客戶端實例。
<?php
class Multiton
{
/** @var array */
private static array $instances = [];
private function __construct(private string $key, private array $config) {}
private function __clone() {}
public function __wakeup() { throw new \Exception('不能反序列化多例'); }
public static function getInstance(string $key, array $config = []): self
{
if (!isset(self::$instances[$key])) {
if (empty($config)) throw new \Exception("首次獲取鍵 '$key' 必須提供配置");
self::$instances[$key] = new self($key, $config);
}
return self::$instances[$key];
}
public static function hasInstance(string $key): bool
{
return isset(self::$instances[$key]);
}
public static function removeInstance(string $key): void
{
unset(self::$instances[$key]);
}
public static function clearInstances(): void
{
self::$instances = [];
}
public function getKey(): string { return $this->key; }
public function getConfig(): array { return $this->config; }
public function doSomething(): void { echo "Multiton[$this->key] working\n"; }
}
// 使用
$dbMaster = Multiton::getInstance('db_master', ['host'=>'10.0.0.1', 'db'=>'master']);
$dbSlave = Multiton::getInstance('db_slave', ['host'=>'10.0.0.2', 'db'=>'slave']);
$redisCache = Multiton::getInstance('redis_cache', ['host'=>'10.0.0.3', 'port'=>6379]);
var_dump($dbMaster === Multiton::getInstance('db_master')); // true
var_dump($dbMaster === $dbSlave); // false
?>
<?php
/**
* @template T of object
*/
class MultitonFactory
{
/** @var array */
private static array $instances = [];
/**
* @param class-string $class
* @param array $config
* @return T
*/
public static function getInstance(string $key, string $class, array $config = []): object
{
if (!isset(self::$instances[$key])) {
if (empty($config)) throw new \Exception("Config required for new instance '$key'");
// 支援構造函數參數自動注入(簡化版)
$ref = new ReflectionClass($class);
self::$instances[$key] = $ref->newInstanceArgs($config);
}
return self::$instances[$key];
}
}
// 使用
$logger = MultitonFactory::getInstance('file_logger', FileLogger::class, ['path'=>'/var/log/app.log']);
$logger2 = MultitonFactory::getInstance('file_logger', FileLogger::class); // 同一實例
?>
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 全局配置管理 | DI 容器 Singleton Scope | 可測試、可替換、生命週期托管 |
| 數據庫連接(單主庫) | DI 容器 Singleton / 連接池 | 避免硬編碼單例,支援多環境 |
| 多數據庫/多 Redis 節點 | Multiton (按配置鍵) | 鍵隔離,運行時動態增減 |
| 多租戶隔離配置/服務 | Multiton (租戶 ID 為鍵) | 每租戶獨立實例,互不干擾 |
| 第三方 API 客戶端 (不同 AppID) | Multiton | 按憑證隔離實例 |
| 舊代碼重構/全局工具類 | 類靜態方法 / 靜態局部變量單例 | 低成本改造,逐步遷移至 DI |
__wakeup() 拋出異常,或實現 Serializable 接口控制。private __clone()。removeInstance()、clearInstances()、或弱引用 WeakMap (PHP 8.0+)。