Writing Clean Code in PHP: A Guide for Those Who Respect Themselves and Their Colleagues

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" Is Not About Pedantry, But About Money and Nerves

\n\n

Imagine you open an old PHP project written a year ago. You open the index.php file, and there it is — a mess of HTML, SQL queries, echo statements, and functions with names like f1(). Sound familiar? If so, you are either a beginner just starting your journey, or an experienced developer who inherited a "legacy" project.

\n\n

Clean code in PHP is not a fashion statement or a team lead's whim. It is a tool that saves hours, nerves, and money. In this article, we will break down how to turn your PHP code from a "dirty draft" into a "clean copy" that will delight you and your colleagues. We will talk about PSR standards, SOLID principles, proper naming, and provide real-world examples. Let's go!

\n\n

1. The Philosophy of Clean Code: Key Principles

\n\n

Before diving into syntax, let's agree on the rules of the game. Clean code is code that:

\n\n
    \n
  • Is understandable without comments (although comments are sometimes needed).
  • \n
  • Is easy to test.
  • \n
  • Is not afraid of refactoring.
  • \n
  • Follows a consistent style throughout the entire project.
  • \n
\n\n

Robert Martin (Uncle Bob) said in his book "Clean Code": "The only way to go fast is to go well." If you write quickly and dirtyly, in a month you will spend 10 times more time debugging. Let's learn from others' mistakes, not our own.

\n\n

2. PSR Standards: Your First Step Towards Order

\n\n

In the PHP world, there are PSR (PHP Standards Recommendations) — recommendations adopted by the community. If you don't use them, you are at least making life harder for yourself and your colleagues who will read your code.

\n\n

2.1 PSR-1 and PSR-12: Basic Coding Style

\n\n

PSR-1 sets general rules, and PSR-12 is an extended style. Here are a few key points:

\n\n
    \n
  • Files should only use <?php or <?=.
  • \n
  • File encoding is UTF-8 without BOM.
  • \n
  • Class names should be in StudlyCaps (e.g., UserController).
  • \n
  • Method and property names should be in camelCase (e.g., getUserName()).
  • \n
  • Indentation is 4 spaces (not tabs!).
  • \n
\n\n

Example of bad code:

\n
<?\nclass user_controller {\n\tfunction Get_User_Name($id) {\n\t\t$name = Db::query("SELECT name FROM users WHERE id=$id");\n\t\treturn $name;\n\t}\n}\n
\n\n

Example of good code (PSR-12):

\n
<?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Controllers;\n\nuse App\\Models\\User;\n\nclass UserController\n{\n    public function getUserName(int $id): ?string\n    {\n        $user = User::find($id);\n        return $user ? $user->getName() : null;\n    }\n}\n
\n\n

See the difference? The second option reads like a book: it's immediately clear what the method does, what data types it accepts and returns.

\n\n

2.2 PSR-4: Autoloading Classes

\n\n

Forget about require_once in every file. Use Composer and PSR-4. This allows classes to be loaded automatically based on namespaces. The folder structure should match the namespaces:

\n\n
src/\n  App/\n    Controllers/\n      UserController.php\n    Models/\n      User.php\n    Services/\n      PaymentService.php\n
\n\n

In composer.json, this is configured with one line:

\n
{\n    "autoload": {\n        "psr-4": {\n            "App\\\\": "src/"\n        }\n    }\n}\n
\n\n

3. Proper Naming: How Not to Name a Variable $a

\n\n

Naming is 50% of success. A bad variable name can confuse even a genius. Let's break down common mistakes.

\n\n

3.1 Avoid Abbreviations (Except Obvious Ones)

Blogs

Book Recommendations