Clean Code in PHP: Principles and Practical Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Clean Code in PHP is Not a Luxury, But a Necessity

Every PHP developer has at least once encountered a situation where a simple bug in a production environment turns into a multi-hour hunt for the "devil in the details." Most often, the reason lies not in the complexity of the logic, but in dirty code: meaningless variable names, functions 500 lines long, lack of types, and misleading comments. Clean Code is not just about aesthetics. It is a tool that reduces project maintenance costs by 3–5 times and allows new team members to get up to speed in hours, not weeks.

In this article, we will break down the key principles of Clean Code as applied to PHP, backing them up with real before-and-after refactoring examples. You will learn how to apply PSR standards, SOLID principles, and simple naming rules so that your code speaks for itself.



1. Naming Variables, Functions, and Classes: Speak the Language of Business

A bad name is the main enemy of readability. If a variable is called $a or $data, every time you read the code, you waste mental resources on deciphering it. The rule is simple: the name should answer the question "What is this?" or "What does it do?"



Bad Example

<?php// What is $d? Why $x = 2?$d = new DateTime();$x = 2;$y = $d->modify('+' . $x . ' days');echo $y->format('Y-m-d');?>


Good Example (Clean Code)

<?php$currentDate = new DateTime();$daysToAdd = 2;$futureDate = $currentDate->modify('+' . $daysToAdd . ' days');echo $futureDate->format('Y-m-d');?>

Additional Rules:

  • Classes and Interfaces — nouns: UserRepository, PaymentGatewayInterface.
  • Methods — verbs: getUserById(), sendEmailNotification().
  • Boolean Variables — prefixes is, has, can: $isActive, $hasPermission.
  • Avoid Abbreviations: $cnt → $count, $usr → $user.


2. Functions and Methods: The Single Responsibility Principle (SRP) in Action

One function — one action. If you see a function longer than 20–30 lines, it can most likely be broken down. In PHP, this is especially relevant, as the lack of strict typing (before PHP 7.4) encourages "code dumps."



Bad Example: Swiss Army Knife Function

<?phpfunction processOrder(array $orderData): array{    // Validation    if (empty($orderData['email'])) {        throw new InvalidArgumentException('Email required');    }    // Save to DB    $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');    $stmt = $pdo->prepare('INSERT INTO orders (email, total) VALUES (?, ?)');    $stmt->execute([$orderData['email'], $orderData['total']]);    // Send email    mail($orderData['email'], 'Order Confirmed', 'Thank you!');    // Logging    file_put_contents('log.txt', 'Order processed: ' . $orderData['email'] . PHP_EOL, FILE_APPEND);    return ['status' => 'success'];}?>


Good Example: Separation of Concerns

<?phpclass OrderProcessor{    private OrderValidator $validator;    private OrderRepository $repository;    private MailService $mailer;    private Logger $logger;

public function __construct( OrderValidator $validator, OrderRepository $repository, MailService $mailer, Logger $logger ) { $this->validator = $validator; $this->repository = $repository; $this->mailer = $mailer; $this->logger = $logger; }

public function process(array $orderData): arr

Blogs

Book Recommendations