Backend Development 8 min read

Common PHP Code Smells and Refactoring Solutions

This article explains typical PHP code smells such as long methods, large classes, duplicate code, excessive comments, complex conditionals, and infinite loops, and provides concrete refactoring examples to improve readability, maintainability, and overall code quality.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Common PHP Code Smells and Refactoring Solutions

Code smells are characteristics or patterns in code that indicate potential problems or inefficiencies; identifying and fixing them is essential for maintaining clean, maintainable, and scalable codebases.

This article examines several common PHP code smells and offers practical examples and solutions.

Long Method

A long method exceeds about 20 lines and often tries to do too many things, making the code hard to understand, test, and extend.

<code>// Example of a long method
class OrderProcessor {
    public function processOrder($order) {
        // ... many lines of code ...
    }
}
</code>

Solution: break the method into smaller, focused functions with clear responsibilities.

<code>class OrderProcessor {
    public function processOrder($order) {
        $this->validateOrder($order);
        $this->calculateTotal($order);
        $this->applyDiscount($order);
        // ... other specific tasks ...
    }

    private function validateOrder($order) {
        // validation logic
    }

    private function calculateTotal($order) {
        // calculation logic
    }

    private function applyDiscount($order) {
        // discount logic
    }
}
</code>

Large Class

A large class contains too many responsibilities and methods, leading to difficulty in understanding, testing, and error proneness.

<code>// Example of a large class
class Order {
    public function process() {
        // ... 处理订单的逻辑 ...
    }

    public function calculateTotal() {
        // ... 计算订单总额的逻辑 ...
    }
    // ... 其他方法 ...
}
</code>

Solution: split the class into smaller, focused classes, each handling a specific aspect.

<code>class Order {
    private $processor;
    private $calculator;

    public function __construct(OrderProcessor $processor, OrderCalculator $calculator) {
        $this->processor = $processor;
        $this->calculator = $calculator;
    }

    public function process() {
        $this->processor->processOrder($this);
    }

    public function calculateTotal() {
        $this->calculator->calculateTotal($this);
    }
}

class OrderProcessor {
    public function processOrder(Order $order) {
        // ... 处理订单的逻辑 ...
    }
}

class OrderCalculator {
    public function calculateTotal(Order $order) {
        // ... 计算订单总额的逻辑 ...
    }
}
</code>

Duplicate Code

Duplicate code appears as identical or similar blocks scattered throughout the codebase, making maintenance hard and increasing error risk.

<code>class UserController {
    public function createUser($data) {
        // ... 验证逻辑 ...
        $user = new User();
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->save();
    }

    public function updateProfile($data) {
        // ... 验证逻辑 ...
        $user = Auth::user();
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->save();
    }
}
</code>

Solution: extract the common functionality into a separate method or class.

<code>class UserController {
    public function createUser($data) {
        $this->validateAndSaveUser($data);
    }

    public function updateProfile($data) {
        $this->validateAndSaveUser($data, Auth::user());
    }

    private function validateAndSaveUser($data, $user = null) {
        // ... validation logic ...
        if (!$user) {
            $user = new User();
        }
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->save();
    }
}
</code>

Excessive Comments

Too many comments make code redundant and harder to read; comments can become outdated or ignored.

<code>// 过度使用注释的示例
class Calculator {
    // 将两个数字相加的函数
    public function add($a, $b) {
        return $a + $b;
    }

    // 两个数字相减的函数
    public function minus($a, $b) {
        return $a - $b;
    }
}
</code>

Solution: write clean, self‑explanatory code that needs minimal commenting.

<code>class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }

    public function subtract($a, $b) {
        return $a - $b;
    }
}
</code>

Complex Conditional Statements

Nested or overly complex conditionals reduce readability and increase error risk.

<code>class PaymentProcessor {
    public function processPayment($order) {
        if ($order->isConfirmed()) {
            if ($order->hasItems()) {
                if ($order->isPaymentDue()) {
                    // 处理付款
                } else {
                    // 付款已完成
                }
            } else {
                // 订单中没有商品
            }
        } else {
            // 订单未确认
        }
    }
}
</code>

Solution: extract validation into separate methods and simplify the flow.

<code>class PaymentProcessor {
    public function processPayment($order) {
        if (! $this->isValidOrder($order)) {
            // 处理无效订单
            return;
        }
        // 处理付款
    }

    private function isValidOrder($order) {
        return $order->isConfirmed() && $order->hasItems() && $order->isPaymentDue();
    }
}
</code>

Infinite Loop

An infinite loop lacks a proper termination condition, potentially hanging or crashing the application.

<code>class TaskScheduler {
    public function runTasks() {
        while ($this->hasPendingTasks()) {
            // 执行任务
            // ...
        }
    }

    private function hasPendingTasks() {
        // 检查是否有待处理的任务
        // 该方法可能没有正确更新状态
    }
}
</code>

Solution: ensure loops have a clear exit condition, such as a maximum iteration count.

<code>class TaskScheduler {
    public function runTasks() {
        $maxIterations = 1000; // prevent potential infinite loop
        for ($i = 0; $i < $maxIterations && $this->hasPendingTasks(); $i++) {
            // 执行任务
            // ...
        }
    }

    private function hasPendingTasks() {
        // 检查是否有待处理的任务
        // ...
    }
}
</code>

By identifying and addressing these PHP code smells, developers can improve code readability, maintainability, and overall quality; applying best practices such as SOLID principles and regular refactoring ensures long‑term project success.

Backendsoftware engineeringPHPrefactoringcode smells
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.