Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

clean-code-php

> 编程语言
Open source

:bathtub: Clean Code concepts adapted for PHP

12.5K stars0 likes6 views
WebsiteGitHub

About

:bathtub: Clean Code concepts adapted for PHP

Clean Code PHP

Table of Contents

  1. Introduction
  2. Variables
    • Use meaningful and pronounceable variable names
    • Use the same vocabulary for the same type of variable
    • Use searchable names (part 1)
    • Use searchable names (part 2)
    • Use explanatory variables
    • Avoid nesting too deeply and return early (part 1)
    • Avoid nesting too deeply and return early (part 2)
    • Avoid Mental Mapping
    • Don't add unneeded context
  3. Comparison
    • Use identical comparison
    • Null coalescing operator
  4. Functions
    • Use default arguments instead of short circuiting or conditionals
    • Function arguments (2 or fewer ideally)
    • Function names should say what they do
    • Functions should only be one level of abstraction
    • Don't use flags as function parameters
    • Avoid Side Effects
    • Don't write to global functions
    • Don't use a Singleton pattern
    • Encapsulate conditionals
    • Avoid negative conditionals
    • Avoid conditionals
    • Avoid type-checking (part 1)
    • Avoid type-checking (part 2)
    • Remove dead code
  5. Objects and Data Structures
    • Use object encapsulation
    • Make objects have private/protected members
  6. Classes
    • Prefer composition over inheritance
    • Avoid fluent interfaces
    • Prefer final classes
  7. SOLID
    • Single Responsibility Principle (SRP)
    • Open/Closed Principle (OCP)
    • Liskov Substitution Principle (LSP)
    • Interface Segregation Principle (ISP)
    • Dependency Inversion Principle (DIP)
  8. Don’t repeat yourself (DRY)
  9. Translations

Introduction

Software engineering principles, from Robert C. Martin's book Clean Code, adapted for PHP. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in PHP.

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

Inspired from clean-code-javascript.

Although many developers still use PHP 5, most of the examples in this article only work with PHP 7.1+.

Variables

Use meaningful and pronounceable variable names

Bad:

php
$ymdstr = $moment->format('y-m-d');

Good:

php
$currentDate = $moment->format('y-m-d');

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:

php
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();

Good:

php
getUser();

⬆ back to top

Use searchable names (part 1)

We will read more code than we will ever write. It's important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.

Bad:

php
// What the heck is 448 for?
$result = $serializer->serialize($data, 448);

Good:

php
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Use searchable names (part 2)

Bad:

php
class User
{
    // What the heck is 7 for?
    public $access = 7;
}

// What the heck is 4 for?
if ($user->access & 4) {
    // ...
}

// What's going on here?
$user->access ^= 2;

Good:

php
class User
{
    public const ACCESS_READ = 1;

    public const ACCESS_CREATE = 2;

    public const ACCESS_UPDATE = 4;

    public const ACCESS_DELETE = 8;

    // User as default can read, create and update something
    public $access = self::ACCESS_READ | self::ACCESS_CREATE | self::ACCESS_UPDATE;
}

if ($user->access & User::ACCESS_UPDATE) {
    // do edit ...
}

// Deny access rights to create something
$user->access ^= User::ACCESS_CREATE;

⬆ back to top

Use explanatory variables

Bad:

php
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);

saveCityZipCode($matches[1], $matches[2]);

Not bad:

It's better, but we are still heavily dependent on regex.

php
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);

[, $city, $zipCode] = $matches;
saveCityZipCode($city, $zipCode);

Good:

Decrease dependence on regex by naming subpatterns.

php
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);

saveCityZipCode($matches['city'], $matches['zipCode']);

⬆ back to top

Avoid nesting too deeply and return early (part 1)

Too many if-else statements can make your code hard to follow. Explicit is better than implicit.

Bad:

php
function isShopOpen($day): bool
{
    if ($day) {
        if (is_string($day)) {
            $day = strtolower($day);
            if ($day === 'friday') {
                return true;
            } elseif ($day === 'saturday') {
                return true;
            } elseif ($day === 'sunday') {
                return true;
            }
            return false;
        }
        return false;
    }
    return false;
}

Good:

php
function isShopOpen(string $day): bool
{
    if (empty($day)) {
        return false;
    }

    $openingDays = ['friday', 'saturday', 'sunday'];

    return in_array(strtolower($day), $openingDays, true);
}

⬆ back to top

Avoid nesting too deeply and return early (part 2)

Bad:

php
function fibonacci(int $n)
{
    if ($n < 50) {
        if ($n !== 0) {
            if ($n !== 1) {
                return fibonacci($n - 1) + fibonacci($n - 2);
            }
            return 1;
        }
        return 0;
    }
    return 'Not supported';
}

Good:

php
function fibonacci(int $n): int
{
    if ($n === 0 || $n === 1) {
        return $n;
    }

    if ($n >= 50) {
        throw new Exception('Not supported');
    }

    return fibonacci($n - 1) + fibonacci($n - 2);
}

⬆ back to top

Avoid Mental Mapping

Don’t force the reader of your code to translate what the variable means. Explicit is better than implicit.

Bad:

php
$l = ['Austin', 'New York', 'San Francisco'];

for ($i = 0; $i < count($l); $i++) {
    $li = $l[$i];
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    // Wait, what is `$li` for again?
    dispatch($li);
}

Good:

php
$locations = ['Austin', 'New York', 'San Francisco'];

foreach ($locations as $location) {
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    dispatch($location);
}

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in your variable name.

Bad:

php
class Car
{
    public $carMake;

    public $carModel;

    public $carColor;

    //...
}

Good:

php
class Car
{
    public $make;

    public $model;

    public $color;

    //...
}

⬆ back to top

Comparison

Use identical comparison

Not good:

The simple comparison will convert the string into an integer.

php
$a = '42';
$b = 42;

if ($a != $b) {
    // The expression will always pass
}

The comparison $a != $b returns FALSE but in fact it's TRUE! The string 42 is different than the integer 42.

Good:

The identical comparison will compare type and value.

php
$a = '42';
$b = 42;

if ($a !== $b) {
    // The expression is verified
}

The comparison $a !== $b returns TRUE.

⬆ back to top

Null coalescing operator

Null coalescing is a new operator introduced in PHP 7. The null coalescing operator ?? has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

Bad:

php
if (isset($_GET['name'])) {
    $name = $_GET['name'];
} elseif (isset($_POST['name'])) {
    $name = $_POST['name'];
} else {
    $name = 'nobody';
}

Good:

php
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';

⬆ back to top

Functions

Use default arguments instead of short circuiting or conditionals

Not good:

This is not good because $breweryName can be NULL.

php
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
    // ...
}

Not bad:

This opinion is more understandable than the previous version, but it better controls the value of the variable.

php
function createMicrobrewery($name = null): void
{
    $breweryName = $name ?: 'Hipster Brew Co.';
    // ...
}

Good:

You can use type hinting and be sure that the $breweryName will not be NULL.

php
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
    // ...
}

⬆ back to top

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.

Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument.

Bad:

php
class Questionnaire
{
    public function __construct(
        string $firstname,
        string $lastname,
        string $patronymic,
        string $region,
        string $district,
        string $city,
        string $phone,
        string $email
    ) {
        //

Issues· 30 open

View all issuesOpen on GitHub
  • #227

    Code Error

    Updated Mar 25, 2025
  • #228

    Unable to create PR due to "Validation failed: must be a collaborator"

    Updated Mar 25, 2025
  • #224

    Cleen code

    Updated Feb 4, 2024
  • #222

    Premier jet du dictionnaire de données

    Updated Nov 2, 2023
  • #130

    "Prefer composition over inheritance": Why you don't use traits?

    Updated Oct 16, 2023
  • #221

    Book PHp

    Updated May 16, 2023
  • #216

    Problem in the fibonacci function

    Updated Feb 13, 2023
  • #213

    adding ndonesian translation section + Refactor code under collapsible markdown

    Updated Nov 28, 2022
  • #212

    Define constants in those methods where you use, not globally

    Updated Nov 6, 2022
  • #51

    introduction of mocking on "Functions should only be one level of abstraction" should be removed

    Updated Oct 4, 2022

> Tags

PHP

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 28, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言