讲师中心 微信公众号

工具推荐

视频效率加速
立刻MV
立刻MV

低成本歌曲 MV、视频生成

Loomy
Loomy

AI助理适用自媒体、办公、日程等场景

AniShort
AniShort

AI短剧协同制作平台

updream

一键生成高质量推广成片

PHP工厂模式怎么配合依赖注入使用

雨丽酱_3492

雨丽酱_3492

发布时间:2026-12-04 07:54:57

|

978人浏览过

|

来源于php中文网

原创

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

PHP工厂模式怎么配合依赖注入使用

ProductFactory接口如何解耦客户端与具体产品类

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

PHP工厂模式怎么配合依赖注入使用

<?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() 方法中负责将这些依赖传递给产品构造函数。这确保了产品对象在被创建时就具备所有必要的依赖,符合依赖倒置原则。工厂类自身也可以通过依赖注入获得这些配置或子服务。

Build MCP servers and clients for PHP applications with the official PHP SDK
Build MCP servers and clients for PHP applications with the official PHP SDK

使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

下载

立即学习“PHP免费学习笔记(深入)”;

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 提供。

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

php

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
UpDream
UpDream Hot

一款AI视频创作工具,主要用于哔哩哔哩推出的自研AI视频创作工具,适合需要提升相关任务效率的用户。

Flowith
Flowith Hot

Flowith是一款基于画布和智能体工作流的 AI 协作工作空间。

超级麦吉

一款通过数字员工协作完成调研、数据分析与文档制作的AI办公平台。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

音述AI
音述AI Hot

一款AI音频处理工具,主要用于音述AI是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区,适合需要提升相关任务效率的用户。

墨刀AI
墨刀AI Hot

一款AI图像与设计工具,主要用于产品经理的专属智能体,适合需要提升相关任务效率的用户。

SpeedAI
SpeedAI Hot

SpeedAI是一款AI论文写作工具,AI科研助手,AIGC检测、降重降AI率。

相关专题

更多
php文件怎么打开
php文件怎么打开

打开php文件步骤:1、选择文本编辑器;2、在选择的文本编辑器中,创建一个新的文件,并将其保存为.php文件;3、在创建的PHP文件中,编写PHP代码;4、要在本地计算机上运行PHP文件,需要设置一个服务器环境;5、安装服务器环境后,需要将PHP文件放入服务器目录中;6、一旦将PHP文件放入服务器目录中,就可以通过浏览器来运行它。

14244

2023.09.01

php怎么取出数组的前几个元素
php怎么取出数组的前几个元素

取出php数组的前几个元素的方法有使用array_slice()函数、使用array_splice()函数、使用循环遍历、使用array_slice()函数和array_values()函数等。本专题为大家提供php数组相关的文章、下载、课程内容,供大家免费下载体验。

8081

2023.10.11

php反序列化失败怎么办
php反序列化失败怎么办

php反序列化失败的解决办法检查序列化数据。检查类定义、检查错误日志、更新PHP版本和应用安全措施等。本专题为大家提供php反序列化相关的文章、下载、课程内容,供大家免费下载体验。

2335

2023.10.11

php怎么连接mssql数据库
php怎么连接mssql数据库

连接方法:1、通过mssql_系列函数;2、通过sqlsrv_系列函数;3、通过odbc方式连接;4、通过PDO方式;5、通过COM方式连接。想了解php怎么连接mssql数据库的详细内容,可以访问下面的文章。

5108

2023.10.23

php连接mssql数据库的方法
php连接mssql数据库的方法

php连接mssql数据库的方法有使用PHP的MSSQL扩展、使用PDO等。想了解更多php连接mssql数据库相关内容,可以阅读本专题下面的文章。

5874

2023.10.23

html怎么上传
html怎么上传

html通过使用HTML表单、JavaScript和PHP上传。更多关于html的问题详细请看本专题下面的文章。php中文网欢迎大家前来学习。

4631

2023.11.03

PHP出现乱码怎么解决
PHP出现乱码怎么解决

PHP出现乱码可以通过修改PHP文件头部的字符编码设置、检查PHP文件的编码格式、检查数据库连接设置和检查HTML页面的字符编码设置来解决。更多关于php乱码的问题详情请看本专题下面的文章。php中文网欢迎大家前来学习。

6717

2023.11.09

php文件怎么在手机上打开
php文件怎么在手机上打开

php文件在手机上打开需要在手机上搭建一个能够运行php的服务器环境,并将php文件上传到服务器上。再在手机上的浏览器中输入服务器的IP地址或域名,加上php文件的路径,即可打开php文件并查看其内容。更多关于php相关问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

5322

2023.11.13

PHP 8.6报错排查指南
PHP 8.6报错排查指南

错误处理和日志记录是PHP应用定位故障、追踪运行状态的重要手段。本专题结合PHP 8.6介绍从本地调试到线上日志管理的常用做法,说明怎样保留有用的错误信息,同时控制堆栈和敏感数据的暴露,便于在问题发生后找到排查线索。

20

2026.12.02

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn