php工厂模式配合依赖注入的核心做法是让工厂类本身作为依赖被注入到客户端,或者让工厂方法返回的实例通过构造函数完成内部依赖的装配。具体而言,应定义一个工厂接口,由具体工厂实现该接口并负责创建具有特定依赖关系的对象实例,客户端仅依赖工厂接口而非具体产品类,从而在运行时灵活替换产品的生成逻辑。若工厂创建的复杂对象包含其他依赖,应在工厂内部使用容器或手动组装这些依赖,确保返回的对象处于完全初始化状态。

ProductFactory接口如何解耦客户端与具体产品类
通过定义抽象工厂接口,客户端代码只依赖于接口类型,从而实现对具体产品类的解耦。这种设计允许在不修改客户端代码的情况下,通过注入不同的工厂实现来改变产品的创建行为。

<?php
// 1. 定义产品接口
interface Notification {
public function send(string $message): void;
}
class EmailNotification implements Notification {
private string $smtpHost;
public function __construct(string $smtpHost) {
$this->smtpHost = $smtpHost;
}
public function send(string $message): void {
echo "Sending email via {$this->smtpHost}: {$message}\n";
}
}
class SmsNotification implements Notification {
private string $apiKey;
public function __construct(string $apiKey) {
$this->apiKey = $apiKey;
}
public function send(string $message): void {
echo "Sending SMS via API Key: {$this->apiKey}: {$message}\n";
}
}
// 2. 定义工厂接口
interface NotificationFactory {
public function create(): Notification;
}
// 3. 具体工厂实现
class EmailNotificationFactory implements NotificationFactory {
private string $host;
public function __construct(string $host) {
$this->host = $host;
}
public function create(): Notification {
return new EmailNotification($this->host);
}
}
class SmsNotificationFactory implements NotificationFactory {
private string $key;
public function __construct(string $key) {
$this->key = $key;
}
public function create(): Notification {
return new SmsNotification($this->key);
}
}
// 4. 客户端代码:依赖注入工厂接口
class UserNotifier {
private NotificationFactory $factory;
// 通过构造函数注入工厂
public function __construct(NotificationFactory $factory) {
$this->factory = $factory;
}
public function notifyUser(string $message): void {
$notification = $this->factory->create();
$notification->send($message);
}
}
// 5. 组装阶段(通常在应用引导脚本中)
$emailFactory = new EmailNotificationFactory('smtp.example.com');
$notifier = new UserNotifier($emailFactory);
$notifier->notifyUser("Hello!");
$smsFactory = new SmsNotificationFactory('abc123-key');
$smsNotifier = new UserNotifier($smsFactory);
$smsNotifier->notifyUser("Hello!");
预期结果:
- 当注入 EmailNotificationFactory 时,输出为:Sending email via smtp.example.com: Hello!
- 当注入 SmsNotificationFactory 时,输出为:Sending SMS via API Key: abc123-key: Hello!
- 客户端 UserNotifier 无需知道具体是邮件还是短信,只需调用 create() 和 send()。
工厂内部如何管理复杂对象的依赖项
当产品对象本身需要多个依赖时,工厂类应在其 create() 方法中负责将这些依赖传递给产品构造函数。这确保了产品对象在被创建时就具备所有必要的依赖,符合依赖倒置原则。工厂类自身也可以通过依赖注入获得这些配置或子服务。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
立即学习“PHP免费学习笔记(深入)”;

<?php
// 假设有一个更复杂的日志记录器
interface Logger {
public function log(string $msg): void;
}
class FileLogger implements Logger {
private string $filePath;
public function __construct(string $filePath) { $this->filePath = $filePath; }
public function log(string $msg): void { echo "File Log: {$msg}\n"; }
}
class DatabaseLogger implements Logger {
private string $dsn;
public function __construct(string $dsn) { $this->dsn = $dsn; }
public function log(string $msg): void { echo "DB Log: {$msg}\n"; }
}
// 复杂产品:通知器,它依赖 Logger
class ComplexNotifier implements Notification {
private Logger $logger;
private string $channel;
public function __construct(Logger $logger, string $channel) {
$this->logger = $logger;
$this->channel = $channel;
}
public function send(string $message): void {
$this->logger->log("Sending to {$this->channel}: {$message}");
echo "Message sent to {$this->channel}\n";
}
}
// 工厂负责组装 ComplexNotifier 的所有依赖
class ComplexNotifierFactory implements NotificationFactory {
private Logger $logger;
private string $channel;
public function __construct(Logger $logger, string $channel) {
$this->logger = $logger;
$this->channel = $channel;
}
public function create(): Notification {
// 工厂内部组装依赖
return new ComplexNotifier($this->logger, $this->channel);
}
}
// 客户端
$client = new UserNotifier(new ComplexNotifierFactory(
new FileLogger('/var/log/app.log'),
'email'
));
$client->notifyUser("Test message");
预期结果:
- 输出:File Log: Sending to email: Test message 和 Message sent to email
- 工厂 ComplexNotifierFactory 接收了 Logger 和 channel 作为构造参数,并在 create() 中将它们传递给 ComplexNotifier。
- 客户端依然只依赖 NotificationFactory 接口,对内部的依赖组装逻辑无感知。
当条件判断决定使用哪种工厂时如何处理
在实际应用中,可能需要根据环境变量、配置文件或请求参数来决定使用哪个具体的工厂。此时,可以使用一个“超级工厂”或“工厂选择器”,它根据条件返回相应的工厂实例。客户端仍然只依赖工厂接口,但创建过程变得动态化。这种做法避免了在客户端代码中出现大量的 if-else 或 switch 语句来判断产品类型。
<?php
// 超级工厂:根据配置返回具体工厂
class NotificationServiceFactory {
public static function createFactory(string $type): NotificationFactory {
return match ($type) {
'email' => new EmailNotificationFactory('smtp.prod.com'),
'sms' => new SmsNotificationFactory('prod-api-key'),
default => throw new InvalidArgumentException("Unknown type: {$type}"),
};
}
}
// 客户端使用超级工厂
$typeFromConfig = 'email'; // 假设从配置读取
$factory = NotificationServiceFactory::createFactory($typeFromConfig);
$notifier = new UserNotifier($factory);
$notifier->notifyUser("Conditional notification");
预期结果:
- 输出:Sending email via smtp.prod.com: Conditional notification
- 如果 $typeFromConfig 改为 'sms',则输出:Sending SMS via API Key: prod-api-key: Conditional notification
- 客户端代码 UserNotifier 保持不变,动态性由 NotificationServiceFactory 提供。


















