当前位置: 首页 > 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.jsqmd.com/news/973491/

相关文章:

  • ADS2017链路预算进阶:手把手教你搞定多端口元件(如双工器、耦合器)的增益与噪声系数仿真
  • 珠宝改款定制镶嵌哪家好:排名前五深度测评 - 服务品牌热点
  • 为什么现代渲染器越来越像数据库
  • 支付宝红包闲置怎么处理?认准正规平台安全回收 - 团团收购物卡回收
  • Qt程序调用WPS导出Word报错?可能是管理员权限在作祟(附VS与Qt Creator对比排查)
  • 告别外围电路!用ESP32-PICO-D4做超小型物联网设备,手把手教你画第一版原理图
  • 大模型中间层为何必然归零:从Anthropic API进化看工程极简主义
  • STM32L151平台下BL55080 LCD芯片的轻量级C驱动代码(SPI/8080接口)
  • 化州母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • 千问 LeetCode 3077. K 个不相交子数组的最大能量值 Go实现
  • Windows XP兼容性开发实战:使用YY-Thunks解决常见API缺失问题
  • 哈尔滨母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • STM32F407主控+ESP32联网的智能家居控制工程(含FreeRTOS多任务调度与陶晶驰HMI界面源码)
  • 2026年海宁市空调维修避坑指南:5家靠谱专业推荐 海宁小李家电维修正规可靠 - 本地品牌推荐
  • Mac Mouse Fix:如何让你的普通鼠标在macOS上比苹果触控板更好用?
  • 广水母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • 从ADS到SystemVue:当简单链路预算不够用时,我的射频系统级仿真方案升级实录
  • 从电磁学到流体力学:散度、旋度、环量、通量到底在描述什么?一张图讲清楚
  • 2026年6月7日更新:最新 Docker 国内镜像源加速列表
  • AI编排:企业级LLM应用落地的数据调度中枢
  • AI 导出鸭实用教程:ChatGPT 和 Gemini 转 pdf,轻松搞定文件格式转换
  • 5个实用技巧:使用kb库高效处理阿拉伯语、印地语等复杂脚本
  • 从一篇大学英语课文,聊聊技术人如何避免成为‘凯文2050’:警惕知识停滞与技能贬值
  • 公主岭母婴除甲醛CMA甲醛检测治理公司深度测评:绿呼吸环保稳居榜首 - 一修哥咨询
  • java知识四(面向对象编程)
  • 字符串与链表刷题集(5.30-6.6)
  • 科研信息流操作系统:arXiv自动化+结构化笔记+知识图谱闭环
  • 新能源车企的整车故障排查标准(15):故障诊断综合案例与思维训练
  • 2026年镇江CPPM课程班期费用怎么核对?众智商学院官网400冯老师资料咨询 - 众智商学院职业教育
  • 第32章:AI辅助去中心化身份(DID)——链上可验证凭证