撤销实现php
撤销操作的实现方法(PHP)
在PHP中实现撤销功能通常涉及记录操作历史并在需要时回退到之前的状态。以下是几种常见的方法:
基于命令模式的设计 通过封装操作为对象,将操作与执行分离,便于记录和撤销。
interface Command {
public function execute();
public function undo();
}
class ConcreteCommand implements Command {
private $receiver;
private $state;
public function __construct(Receiver $receiver) {
$this->receiver = $receiver;
}
public function execute() {
$this->state = $this->receiver->getState();
$this->receiver->action();
}
public function undo() {
$this->receiver->setState($this->state);
}
}
使用备忘录模式 保存对象状态到备忘录对象,需要时恢复。
class Originator {
private $state;
public function setState($state) {
$this->state = $state;
}
public function saveToMemento() {
return new Memento($this->state);
}
public function restoreFromMemento(Memento $memento) {
$this->state = $memento->getState();
}
}
class Memento {
private $state;
public function __construct($state) { $this->state = $state; }
public function getState() { return $this->state; }
}
数据库事务回滚 对于数据库操作,可直接使用事务机制。
$pdo->beginTransaction();
try {
// 执行SQL操作
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}
栈式操作记录 用数组栈存储操作历史,撤销时弹出并反向执行。

$history = [];
function executeOperation($operation) {
global $history;
$history[] = $operation;
// 执行操作
}
function undo() {
global $history;
$operation = array_pop($history);
// 执行反向操作
}
实现要点
- 需要区分可撤销操作和不可撤销操作
- 考虑设置撤销栈深度限制防止内存溢出
- 对于复杂对象,注意深度克隆问题
- 数据库操作建议优先使用事务机制
性能优化建议
- 对于大对象状态保存,可采用序列化存储
- 频繁操作场景建议使用增量记录而非全量快照
- 内存紧张时可考虑持久化到临时文件






