PHP:调用子类实现的方法时如何自动触发父类默认功能?
解决方案:模板方法模式实现自动日志触发
当然可行!这种场景用模板方法模式来实现再合适不过了——父类负责定义通用的流程框架(比如日志记录+核心业务逻辑),子类只需要专注实现具体的业务细节就行。
核心思路是:父类对外暴露一个非抽象的send()方法,里面包含默认的日志逻辑,然后调用一个子类必须实现的抽象方法(比如doSend())来完成具体发送操作。这样当你调用子类的send()方法时,会自动先执行父类的日志逻辑,再执行子类的核心发送代码。
完整示例代码
抽象父类 CommunicationService
abstract class CommunicationService { // 对外公开的发送方法,封装了日志+核心逻辑的流程 public function send($message) { // 父类的默认日志功能 $this->log("Initiating send operation: " . $message); // 委托给子类实现具体发送逻辑 $this->doSend($message); // 也可以在发送完成后添加日志 $this->log("Send operation completed"); } // 子类必须实现的核心发送逻辑 abstract protected function doSend($message); // 接收方法同理,复用模板模式 public function receive() { $this->log("Starting receive operation"); $result = $this->doReceive(); $this->log("Receive operation finished, result: " . $result); return $result; } abstract protected function doReceive(); // 私有日志方法,封装日志实现细节 private function log($content) { // 这里可以替换为文件日志、数据库日志等实际实现 echo date('[Y-m-d H:i:s] ') . $content . PHP_EOL; } }
子类示例 EmailService
class EmailService extends CommunicationService { // 实现核心发送逻辑 protected function doSend($message) { // 这里写具体的邮件发送代码 echo "✅ Email sent successfully: " . $message . PHP_EOL; } // 实现核心接收逻辑 protected function doReceive() { // 这里写具体的邮件接收代码 return "📧 New email from support@example.com"; } }
调用测试
$emailService = new EmailService(); $emailService->send("Hello, this is a test email!"); echo PHP_EOL; $receivedMsg = $emailService->receive();
执行效果
运行上述代码会输出:
[2024-05-20 14:30:00] Initiating send operation: Hello, this is a test email! ✅ Email sent successfully: Hello, this is a test email! [2024-05-20 14:30:00] Send operation completed [2024-05-20 14:30:00] Starting receive operation [2024-05-20 14:30:00] Receive operation finished, result: 📧 New email from support@example.com
设计优势
- 代码复用:所有子类自动继承父类的日志功能,无需重复编写日志代码
- 统一流程:父类控制业务流程,确保日志逻辑一定会被执行(可以把
send()设为final防止子类重写) - 易于维护:如果需要修改日志规则,只需要修改父类的
log()方法,所有子类都会自动生效
内容的提问来源于stack exchange,提问作者Waqas
相关产品推荐
相关产品推荐

