发布于2026-04-19 阅读(0)
扫一扫,手机访问

本文介绍一种结合接口、代理模式与自动加载机制的通知系统实现方案,既严格遵循开闭原则(对扩展开放、对修改关闭),又避免工厂预实例化所有类导致的内存浪费,适合多类型、低频触发的 PHP 通知场景。
本文介绍一种结合接口、代理模式与自动加载机制的通知系统实现方案,既严格遵循开闭原则(对扩展开放、对修改关闭),又避免工厂预实例化所有类导致的内存浪费,适合多类型、低频触发的 PHP 通知场景。
在构建可维护的 PHP 面向对象通知系统时,核心挑战在于:既要支持任意新增通知类型(如 CommentNotification、FollowNotification),又不能每次添加新类型都修改核心调度逻辑——这正是开闭原则(Open/Closed Principle) 的典型诉求。此前常见的静态工厂模式需硬编码分支判断,违背该原则;而注册式工厂虽开放扩展,却强制提前实例化全部通知类,造成内存冗余与启动开销。
更优解是采用 「接口 + 动态代理」模式,其关键设计如下:
使用 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;
}
}
}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 属性明确返回类型。
前端或 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();
}该方案以极简设计同时满足架构原则与工程实效——不改一行核心代码即可接入第 100 种通知类型,且每个请求仅消耗其真正需要的资源。
上一篇:腾讯会议视频下载与安装教程
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8