基于代理的PHP通知系统:兼顾扩展与效率
本文介绍一种结合接口、代理模式与自动加载机制的通知系统实现方案,既严格遵循开闭原则(对扩展开放、对修改关闭),又避免工厂预实例化所有类导致的内存浪费,适合多类型、低频触发的PHP通知场景。

本文介绍一种结合接口、代理模式与自动加载机制的通知系统实现方案,既严格遵循开闭原则(对扩展开放、对修改关闭),又避免工厂预实例化所有类导致的内存浪费,适合多类型、低频触发的 PHP 通知场景。
本文介绍一种结合接口、代理模式与自动加载机制的通知系统实现方案,既严格遵循开闭原则(对扩展开放、对修改关闭),又避免工厂预实例化所有类导致的内存浪费,适合多类型、低频触发的 PHP 通知场景。
在构建可维护的 PHP 面向对象通知系统时,核心挑战在于:既要支持任意新增通知类型(如 CommentNotification、FollowNotification),又不能每次添加新类型都修改核心调度逻辑——这正是开闭原则(Open/Closed Principle) 的典型诉求。此前常见的静态工厂模式需硬编码分支判断,违背该原则;而注册式工厂虽开放扩展,却强制提前实例化全部通知类,造成内存冗余与启动开销。
更优解是采用 「接口 + 动态代理」模式,其关键设计如下:
✅ 1. 定义统一契约:接口替代抽象类
使用 NotificationInterface 明确行为契约,比继承抽象类更灵活,也更契合“组合优于继承”的实践:
interface NotificationInterface {
public function notify(array $userSettings = []): void;
}每个具体通知类仅需实现该接口,无需共享构造逻辑或状态:
class LikesNotification implements NotificationInterface {
public function notify(array $userSettings = []): void {
if ($userSettings['likes_enabled'] ?? true) {
echo "? You received a new like!" . PHP_EOL;
}
}
}
class AddRequestNotification implements NotificationInterface {
public function notify(array $userSettings = []): void {
if ($userSettings['requests_enabled'] ?? true) {
echo "? New connection request received." . PHP_EOL;
}
}
}✅ 2. 构建轻量代理:按需加载,零预实例化
NotificationProxy 不持有任何具体实例,仅在方法调用时动态解析类名、延迟加载并转发调用,彻底规避内存占用问题:
class NotificationProxy {
private ?NotificationInterface $instance = null;
private string $className;
public function __construct(string $type) {
// 约定命名规范:'Likes' → 'LikesNotification'
$this->className = ucfirst($type) . 'Notification';
}
public function __call(string $method, array $arguments) {
// 首次调用时才实例化(懒加载)
if ($this->instance === null) {
if (!class_exists($this->className)) {
throw new InvalidArgumentException("Notification class '{$this->className}' not found.");
}
$this->instance = new $this->className();
}
return $this->instance->{$method}(...$arguments);
}
}? 优势说明:
- ✅ 开闭原则达标:新增通知类型只需创建新类(如 CommentNotification.php),无需修改代理、工厂或路由逻辑;
- ✅ 内存零浪费:仅当实际调用 $proxy->notify() 时才加载并实例化对应类;
- ✅ 自动加载友好:配合 spl_autoload_register(),类文件按需载入,无冗余 I/O;
- ✅ 类型安全增强(PHP 8+):可为 __call() 添加 @return mixed 或使用 ReturnTypeWillChange 属性明确返回类型。
✅ 3. 实际调用:简洁、语义清晰
前端或 API 层根据 JSON 中的 type 字段直接驱动代理,代码即文档:
// 假设接收请求:{"type": "Likes", "user_id": 123}
$data = json_decode(file_get_contents('php://input'), true);
$userSettings = getUserSettings($data['user_id']); // 自定义获取用户设置
try {
$proxy = new NotificationProxy($data['type']);
$proxy->notify($userSettings); // 自动触发 LikesNotification::notify()
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo "Invalid notification type: " . $e->getMessage();
}⚠️ 注意事项与最佳实践
- 类名约定必须严格:确保 NotificationProxy 中的 $type 到类名映射(如 'likes' → 'LikesNotification')与文件命名一致(LikesNotification.php);
- 异常处理不可省略:class_exists() 检查 + 友好错误提示,避免生产环境因拼写错误导致静默失败;
- 考虑依赖注入:若通知类需数据库连接等服务,可将 NotificationProxy 改造为接受容器(如 Psr\Container\ContainerInterface),在实例化时注入依赖;
- 性能补充:高频场景下可缓存已加载类的反射信息,但绝大多数通知系统无需此优化。
该方案以极简设计同时满足架构原则与工程实效——不改一行核心代码即可接入第 100 种通知类型,且每个请求仅消耗其真正需要的资源。


































