当前位置: 首页 > news >正文

PHP代码重构与设计改善

PHP代码重构与设计改善

重构是改善既有代码设计而不改变外部行为的过程。今天说说PHP代码重构的常见模式和技巧。

提取方法是最常用的重构手法。

```php
// 重构前
class OrderProcessor
{
public function process(array $order): array
{
$total = 0;
foreach ($order['items'] as $item) {
$total += $item['price'] * $item['quantity'];
}
if ($order['coupon'] !== null) {
$total = $total * 0.9;
}
if ($total > 100) {
$total = $total * 0.95;
}
$order['total'] = $total;
$log = date('Y-m-d H:i:s') . " 订单金额: $total\n";
file_put_contents('/tmp/orders.log', $log, FILE_APPEND);
return $order;
}
}

// 重构后
class OrderProcessorRefactored
{
public function process(array $order): array
{
$total = $this->calculateTotal($order);
$order['total'] = $total;
$this->logProcessing($order);
return $order;
}

private function calculateTotal(array $order): float
{
$total = $this->calculateItemsTotal($order['items']);
$total = $this->applyCoupon($total, $order['coupon'] ?? null);
$total = $this->applyBulkDiscount($total);
return $total;
}

private function calculateItemsTotal(array $items): float
{
$total = 0;
foreach ($items as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}

private function applyCoupon(float $total, ?string $coupon): float
{
return $coupon !== null ? $total * 0.9 : $total;
}

private function applyBulkDiscount(float $total): float
{
return $total > 100 ? $total * 0.95 : $total;
}

private function logProcessing(array $order): void
{
$log = date('Y-m-d H:i:s') . " 订单金额: {$order['total']}\n";
file_put_contents('/tmp/orders.log', $log, FILE_APPEND);
}
}
?>

替换条件逻辑为多态。

```php
interface FeeStrategy
{
public function calculate(float $amount): float;
}

class NormalFee implements FeeStrategy
{
public function calculate(float $amount): float { return $amount * 0.01; }
}

class VipFee implements FeeStrategy
{
public function calculate(float $amount): float { return $amount * 0.005; }
}

class PremiumFee implements FeeStrategy
{
public function calculate(float $amount): float { return 0; }
}

class FeeCalculator
{
public function __construct(private FeeStrategy $strategy) {}

public function calculate(float $amount): float
{
return $this->strategy->calculate($amount);
}
}
?>

引入参数对象。

```php
// 重构前
function searchUsers(string $name, string $email, int $age, string $status, int $page, int $perPage): array
{
return [];
}

// 重构后
class SearchCriteria
{
public function __construct(
public ?string $name = null,
public ?string $email = null,
public ?int $age = null,
public ?string $status = null,
public int $page = 1,
public int $perPage = 20,
) {}
}

function searchUsers(SearchCriteria $criteria): array
{
return [];
}

$criteria = new SearchCriteria(name: '张三', status: 'active');
searchUsers($criteria);
?>

分解复杂条件。

```php
// 重构前
if ($user['status'] === 'active' && $user['balance'] > 0 && !$user['frozen'] && $user['verified']) {
// 处理
}

// 重构后
function canProcessPayment(array $user): bool
{
return $user['status'] === 'active'
&& $user['balance'] > 0
&& !$user['frozen']
&& $user['verified'];
}

if (canProcessPayment($user)) {
// 处理
}
?>

重构的核心原则是每次只改一点,保持测试通过。提取方法、替换条件为多态、引入参数对象,这些是常用的重构手法。好的代码不是一次写出来的,是不断重构打磨出来的。

http://www.rkmt.cn/news/1485218.html

相关文章:

  • 2026 南宁卖金防坑,闲置黄金高价变现选这家 - 奢侈品回收评测
  • 为什么现代渲染器越来越像数据库
  • 千问 LeetCode 3077. K 个不相交子数组的最大能量值 Go实现
  • 化州母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • 哈尔滨母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • STM32F407主控+ESP32联网的智能家居控制工程(含FreeRTOS多任务调度与陶晶驰HMI界面源码)
  • 2026年海宁市空调维修避坑指南:5家靠谱专业推荐 海宁小李家电维修正规可靠 - 本地品牌推荐
  • 广水母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • AI编排:企业级LLM应用落地的数据调度中枢
  • 从一篇大学英语课文,聊聊技术人如何避免成为‘凯文2050’:警惕知识停滞与技能贬值
  • 2026年镇江CPPM课程班期费用怎么核对?众智商学院官网400冯老师资料咨询 - 众智商学院职业教育
  • PHP代码迁移与版本升级指南
  • 手把手教你用RT-Thread点亮CH32V307开发板的LED,并搞定串口打印(附完整工程)
  • 【Redis分布式缓存实战】第18章 Redis全方位性能调优
  • RAGFlow 使用指南:从部署到构建 AI 知识库
  • PID无线调参进阶:基于HC-05蓝牙和SerialPlot,打造你的移动调试工作站
  • 别再只测平面了!手把手教你用Apriltag和Homography矩阵实现3D姿态解算
  • 富阳母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • 拒绝暴力洗稿!2026年实测横评10款免费降AI工具:搞定去AIGC痕迹与学术表达双标准 - 降AI实验室
  • 2026电脑显示器选购:高端方案解析与避坑指南 - 服务品牌热点
  • 多 SIM 协作 (DSDS/DSDA) 架构文档
  • GPT-4的1.8万亿参数与2%激活真相:MoE路由机制深度解析
  • 不背单词里没有的单词
  • 2025-2026年上海搬家公司推荐:五大口碑产品评测大件搬运防磕碰市场份额价格 - 品牌推荐
  • 功耗管理与唤醒锁 (WakeLock) 架构文档
  • 玩转SSD1306的8种扫描模式:用Arduino实现OLED动画和特殊显示效果
  • 你的AR/机器人‘眼睛’准吗?手把手教你用手机和A4纸完成相机标定与精度验证
  • 别再复制粘贴了!手把手教你理解CMSIS-DAP离线下载器里那串神秘代码(附ARM反汇编实战)
  • 广州母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • Qt调用WPS导出Word报告踩坑记:管理员权限竟是罪魁祸首?