编写整洁的 PHP 代码

发布时间:2019-08-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了编写整洁的 PHP 代码脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

clipboard.png

简评: Clean Code PHP,是基于罗伯特·马丁的经典编程书籍 ——「代码整洁之道」的 PHP 适用版本,并不是一个风格指南,而是在
PHP 中编写可读、可重用和可重构的软件的指南。当然切忌机械地遵循这里的原则。

不添加不需要的上下文

如果你的类名或对象名称有具体的含义,请不要重复该变量的名称。
差:

<?php

class Car
{
    public $carMake;
    public $carModel;
    public $carColor;

    //...
}

好:

<?php

class Car
{
    public $make;
    public $model;
    public $color;

    //...
}

函数参数数量(理想情况是 2 个以下)

限制函数参数的数量是非常重要的,因为它让函数更容易测试,参数超过三个的话,你必须用每个单独的参数测试大量不同的情况。

无参数是理想的情况。一个或两个参数是可以的,但应该避免三个。通常,如果你有两个以上的参数,那么你的函数试图完成太多的功能,若不是,大多数时候,较高级的对象就足以作为参数(译者注:比如数组、对象)。

差:

<?php

function createMenu($tITle, $body, $buttonText, $cancellable) {
    // ...
}

好:

<?php 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) {
    // ...
}

一个函数应该只完成一件事

这是软件工程中最重要的规则。当函数做的事多于一件事情时,他们更难编写和测试。 当你可以将函数隔离成一个动作时,可以轻松重构,代码也将更易读

差:

<?php

function emailClients($clients) {
    foreach ($clients as $client) {
        $clientRecord = $db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
}

好:

function emailClients($clients) {
    $activeClients = activeClients($clients);
    array_walk($activeClients, 'email');
}

function activeClients($clients) {
    return array_filter($clients, 'isClientActive');
}

function isClientActive($client) {
    $clientRecord = $db->find($client);
    return $clientRecord->isActive();
}

使用 get 和 set 方法

在 PHP 中,可以为方法设置 public、PRotected 和 private 关键字,可以控制对象上的属性可见性。这是面向对象的设计原则中的开放/封闭原则的一部分。

差:

class BankAccount
{
    public $balance = 1000;
}

$bankAccount = new BankAccount();

// Buy shoes...
$bankAccount->balance -= 100;

好:

class BankAccount
{
    private $balance;

    public function __construct($balance = 1000)
    {
      $this->balance = $balance;
    }

    public function withdrawBalance($amount)
    {
        if ($amount > $this->balance) {
            throw new Exception('Amount greater than available balance.');
        }

        $this->balance -= $amount;
    }

    public function depositBalance($amount)
    {
        $this->balance += $amount;
    }

    public function getBalance()
    {
        return $this->balance;
    }
}

$bankAccount = new BankAccount();

// Buy shoes...
$bankAccount->withdrawBalance($shoesPrice);

// Get balance
$balance = $bankAccount->getBalance();

原文:Clean Code Concepts Adapted for PHP

脚本宝典总结

以上是脚本宝典为你收集整理的编写整洁的 PHP 代码全部内容,希望文章能够帮你解决编写整洁的 PHP 代码所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。