php实现电梯
PHP实现电梯逻辑
电梯系统的核心逻辑包括状态管理、请求处理和移动控制。以下是一个简化的PHP实现方案:
电梯类结构
class Elevator {
private $currentFloor = 1;
private $direction = 'idle'; // 'up', 'down', 'idle'
private $requestedFloors = [];
private $maxFloor;
public function __construct($maxFloor) {
$this->maxFloor = $maxFloor;
}
}
请求处理方法
public function requestFloor($floor) {
if ($floor > $this->maxFloor || $floor < 1) {
throw new Exception("Invalid floor request");
}
if (!in_array($floor, $this->requestedFloors)) {
$this->requestedFloors[] = $floor;
$this->determineDirection();
}
}
方向决策逻辑
private function determineDirection() {
if (empty($this->requestedFloors)) {
$this->direction = 'idle';
return;
}
$higherFloors = array_filter($this->requestedFloors,
fn($f) => $f > $this->currentFloor);
$lowerFloors = array_filter($this->requestedFloors,
fn($f) => $f < $this->currentFloor);
if ($this->direction === 'up' && !empty($higherFloors)) return;
if ($this->direction === 'down' && !empty($lowerFloors)) return;
$this->direction = !empty($higherFloors) ? 'up' :
(!empty($lowerFloors) ? 'down' : 'idle');
}
移动控制
public function move() {
if ($this->direction === 'idle') return;
$nextFloor = $this->currentFloor + ($this->direction === 'up' ? 1 : -1);
echo "Moving from {$this->currentFloor} to {$nextFloor}\n";
$this->currentFloor = $nextFloor;
if (in_array($nextFloor, $this->requestedFloors)) {
$this->stopAtFloor($nextFloor);
}
}
private function stopAtFloor($floor) {
$index = array_search($floor, $this->requestedFloors);
unset($this->requestedFloors[$index]);
echo "Stopping at floor {$floor}\n";
$this->determineDirection();
}
使用示例
$elevator = new Elevator(10);
$elevator->requestFloor(5);
$elevator->requestFloor(3);
$elevator->requestFloor(7);
while (true) {
$elevator->move();
sleep(1); // 模拟移动时间
}
数据库设计
对于需要持久化的电梯系统,建议的MySQL表结构:
CREATE TABLE elevator_requests (
id INT AUTO_INCREMENT PRIMARY KEY,
floor_number INT NOT NULL,
direction ENUM('up', 'down') NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status ENUM('pending', 'completed') DEFAULT 'pending'
);
CREATE TABLE elevator_status (
elevator_id INT PRIMARY KEY,
current_floor INT DEFAULT 1,
direction ENUM('up', 'down', 'idle') DEFAULT 'idle',
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
优化方向
- 实现SCAN算法(电梯扫描算法)提高效率
- 添加重量传感器等安全限制
- 支持多电梯协同调度
- 添加紧急停止功能
- 实现楼层呼叫按钮的模拟
注意事项
- 需要处理并发请求的场景
- 实际应用中应考虑加入状态锁机制
- 移动时间应根据楼层高度动态计算
- 建议使用队列处理外部请求
- 需要添加异常处理(如超载、故障等)







