/ Software Development

Some Examples to Write Clean Code in PHP

Md. Mahmud Ur Rahman

Md. Mahmud Ur Rahman

Read more posts by this author.

Read More
Some Examples to Write Clean Code in PHP

In this article I will present some guidelines on how to write clean, reusable, readable and refactorable code in PHP.

Not every principle in this article has to be strictly followed. These are just some guidelines and nothing more. This guidelines are codified over many years of collective experience by the renowned author Robert C. Martin in his book "Clean Code: A Handbook of Agile Software Craftsmanship". There he describes the best coding practices which every programmer should follow.

Use Meaningful Variable Name

Example 1:

Bad

$d = $c->toFormattedDateString();

Good

$current_date = $carbon->toFormattedDateString();

Example 2:

Bad

$a = $student->all()->count();
// Or Don't be lazy
$total_s = $student->all()->count();

Good

$total_students = $student->all()->count();

Use Searchable Names

Example 1:

Bad

$gross_total = $total_price * 0.04;  // What is 0.04?

Good

define("TAX_RATE", 0.04);
$gross_total = $total_price * TAX_RATE;

Example 2:

Bad

if($order->status === 2){	// What is 2?
	$order->ship();
}

Good

Class OrderStatus{
	const PAYMENT_FAILED = 'PAYMENT_FAILED';
      const PAYMENT_SUCCESS = 'PAYMENT_SUCCESS';
}

if($order->status === OrderStatus::PAYMENT_SUCCESS){
	$order->ship();
}

Avoid Nesting Too Deeply

Too many if-else statements can make your code hard to follow.

Example 1:

Bad

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;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Good

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

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

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

Example 2:

Bad

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

Good

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);
}

Avoid Mental Mapping

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

Example:

Bad

$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

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

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

2 or Fewer Arguments in Methods

Example:

Bad

function createMenu(string $title, string $body, string $buttonText, bool $cancellable): void
{
    // ...
}

Good

class MenuConfig
{
    public $title;
    public $body;
    public $buttonText;
    public $cancellable = false;
}

$config = new MenuConfig();
$config->title = 'Foo';
$config->body = 'Bar';
$config->buttonText = 'Baz';
$config->cancellable = true;

function createMenu(MenuConfig $config): void
{
    // ...
}

Function Names Should Say What They Do

Example:

Bad

class Email
{
    //...

    public function handle(): void
    {
        mail($this->to, $this->subject, $this->body);
    }
}

$message = new Email(...);
// What is this? A handle for the message? Are we writing to a file now?
$message->handle();

Good

class Email 
{
    //...

    public function send(): void
    {
        mail($this->to, $this->subject, $this->body);
    }
}

$message = new Email(...);
// Clear and obvious
$message->send();

Don't Use Flags as Function Parameters

Example:

Bad

function createFile(string $name, bool $temp = false): void
{
    if ($temp) {
        touch('./temp/'.$name);
    } else {
        touch($name);
    }
}

Good

function createFile(string $name): void
{
    touch($name);
}

function createTempFile(string $name): void
{
    touch('./temp/'.$name);
}

Encapsulate Conditionals

Example:

Bad

if ($article->state === 'published') {
    // ...
}

Good

if ($article->isPublished()) {
    // ...
}

Final Word

Hope these examples help you understanding clean code in PHP. These examples are followed by the best software development company. Just follow the basic principles to get more grip on it.

If you have any questions regarding clean code principles, ask in the comment section.