
本文介绍一种结合代理模式与自动加载机制的通知系统实现方案,既满足开闭原则(新增通知类型无需修改工厂代码),又避免传统工厂预实例化导致的内存浪费。
本文介绍一种结合代理模式与自动加载机制的通知系统实现方案,既满足开闭原则(新增通知类型无需修改工厂代码),又避免传统工厂预实例化导致的内存浪费。
在构建可维护、可扩展的 PHP 通知系统时,核心挑战在于:既要支持任意数量的通知类型(如 LikesNotification、AddRequestNotification),又要确保系统遵循开闭原则(Open/Closed Principle)——即对扩展开放、对修改关闭。常见工厂模式(如 if-else 或 switch 分支判断)虽直观,但每新增一种通知类型就必须修改工厂类,违反 OCP;而“注册式工厂”(提前实例化所有通知类并缓存)虽满足 OCP,却造成不必要的内存占用与初始化开销(尤其当通知逻辑涉及数据库连接、外部 API 调用等重型操作时)。
理想的解决方案应具备以下特性:
✅ 新增通知类型仅需添加新类文件,无需改动任何已有代码;
✅ 通知类仅在真正被调用时才实例化(懒加载);
✅ 保持接口统一,调用方无需感知具体实现细节;
✅ 兼容 PHP 自动加载机制,提升工程可维护性。
我们采用 代理模式(Proxy Pattern) + 命名约定 + __call() 魔术方法 实现这一目标:
1. 定义统一接口
首先定义清晰契约,所有通知类型必须实现该接口:
interface NotificationInterface
{
public function notify(array $user_settings = []): void;
}✅ 注意:notify() 方法接受 $user_settings 参数(如原文需求),便于后续做用户偏好校验(例如:if ($user_settings['likes_enabled'] ?? false) { ... })。
立即学习“PHP免费学习笔记(深入)”;
2. 实现具体通知类(命名需遵循约定)
类名严格遵循 {Type}Notification 格式(如 "Likes" → LikesNotification),便于代理动态解析:
// LikesNotification.php
class LikesNotification implements NotificationInterface
{
public function notify(array $user_settings = []): void
{
if (($user_settings['likes_enabled'] ?? true) === false) {
return; // 用户已关闭该通知
}
echo "Likes Notification content\n";
}
}
// AddRequestNotification.php
class AddRequestNotification implements NotificationInterface
{
public function notify(array $user_settings = []): void
{
if (($user_settings['requests_enabled'] ?? true) === false) {
return;
}
echo "Add Request Notification Content\n";
}
}3. 构建智能代理类(核心)
NotificationProxy 不持有具体实例,而是在方法调用时按需创建并转发:
class NotificationProxy
{
private ?NotificationInterface $instance = null;
private string $type;
public function __construct(string $type)
{
$this->type = $type;
}
public function __call(string $name, array $arguments)
{
// 懒加载:首次调用 notify() 时才实例化
if ($this->instance === null) {
$className = $this->type . 'Notification';
if (!class_exists($className)) {
throw new InvalidArgumentException("Notification class '{$className}' not found.");
}
$this->instance = new $className();
}
// 确保调用的是接口定义的方法(防御性检查)
if (!method_exists($this->instance, $name)) {
throw new BadMethodCallException("Method '{$name}' not supported on notification '{$this->type}'.");
}
return $this->instance->{$name}(...$arguments);
}
}4. 使用示例(简洁且可扩展)
配合标准 PSR-4 自动加载(或简单 spl_autoload_register),调用方极简:
// index.php
spl_autoload_register(function ($class) {
$file = __DIR__ . '/notifications/' . $class . '.php';
if (file_exists($file)) {
require_once $file;
}
});
// 从 JSON 请求中提取 type 字段(如 {"type": "Likes"})
$jsonInput = json_decode(file_get_contents('php://input'), true);
$type = $jsonInput['type'] ?? 'Likes';
// 一行代码完成:路由 + 实例化 + 执行
$proxy = new NotificationProxy($type);
$proxy->notify(['likes_enabled' => true, 'requests_enabled' => false]);✅ 方案优势总结
| 维度 | 传统工厂 | 注册式工厂 | 代理模式(本文) |
|---|---|---|---|
| 开闭原则 | ❌ 需修改工厂 | ✅ 仅注册即可 | ✅ 新增类即生效 |
| 内存效率 | ✅ 按需实例化 | ❌ 全部预加载 | ✅ 真正按需(首次调用) |
| 耦合度 | 工厂强依赖子类 | 工厂强依赖实例 | 零耦合(仅依赖类名约定) |
| 可测试性 | 中等(需 mock 工厂) | 较高 | 极高(可直接 new 具体类) |
⚠️ 注意事项:
- 类名约定是关键,建议在团队规范中明确(如 CamelCase + Notification 后缀);
- 生产环境务必启用 OPcache 并配置合理自动加载策略;
- 可进一步封装为服务容器(如 Symfony DI)中的工厂服务,增强依赖注入能力;
- 若需更严格的类型安全,可引入 ReflectionClass 校验实现接口,而非仅依赖 class_exists()。
此方案以最小侵入性达成架构演进目标:让通知系统真正成为“插件化”的可扩展模块,每一次新通知类型的加入,都只是增加一个符合约定的 PHP 文件——这正是面向对象设计优雅性的体现。



















