• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP代码规范

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

变量

使用见字知意的变量名

坏:

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

好:

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

同一个实体要用相同的变量名

坏:

getUserInfo();

getUserData();

getUserRecord();

getUserProfile();

好:

getUser();

 

使用便于搜索的名称 (part 1)

写代码是用来读的。所以写出可读性高、便于搜索的代码至关重要。 命名变量时如果没有有意义、不好理解,那就是在伤害读者。 请让你的代码便于搜索。

坏:

if ($user->access & 4) {

    // ...

}

好:

class UserEnum

{

    const ACCESS_READ = 1;

    const ACCESS_CREATE = 2;

    const ACCESS_UPDATE = 4;

    const ACCESS_DELETE = 8;

}

 

if ($user->access & User::ACCESS_UPDATE) {

    // do edit ...

}

使用自解释型变量

坏:

$address = 'One Infinite Loop, Cupertino 95014';

$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';

preg_match($cityZipCodeRegex, $address, $matches);

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

好:

使用带名字的子规则,不用懂正则也能看的懂

$address = 'One Infinite Loop, Cupertino 95014';

$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';

preg_match($cityZipCodeRegex, $address, $matches);

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

避免深层嵌套,尽早返回 (part 1)

太多的if else语句通常会导致你的代码难以阅读,直白优于隐晦

糟糕:
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;
    }
}

好:

function isShopOpen(string $day): bool
{
    if (empty($day)) {
        return false;
    }
    $openingDays = [
        'friday', 'saturday', 'sunday'
    ];
    return in_array(strtolower($day), $openingDays, true);
}

避免深层嵌套,尽早返回 (part 2)

糟糕的:
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';
    }
}

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

少用无意义的变量名

别让读你的代码的人猜你写的变量是什么意思。 写清楚好过模糊不清。

坏:

$l = ['Austin', 'New York', 'San Francisco'];
for ($i = 0; $i < count($l); $i++) {
    $li = $l[$i];
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
  // 等等, `$li` 又代表什么?
    dispatch($li);
}

好:
$locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) {
    doStuff();
    doSomeOtherStuff();
    // ...
    // ...
    // ...
    dispatch($location);
}

不要添加不必要上下文

如果从你的类名、对象名已经可以得知一些信息,就别再在变量名里重复。

坏:
class Car
{
    public $carMake;
    public $carModel;
    public $carColor;
    //...
}

好:
class Car
{
    public $make;
    public $model;
    public $color;
    //...
}

合理使用参数默认值,没必要在方法里再做默认值检测

不好,$breweryName 可能为 NULL.
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
    // ...
}

还行:
比上一个好理解一些,但最好能控制变量的值
function createMicrobrewery($name = null): void
{
    $breweryName = $name ?: 'Hipster Brew Co.';
    // ...
}

好:
如果你的程序只支持 PHP 7+, 那你可以用 type hinting 保证变量 $breweryName 不是 NULL.
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
    // ...
}

函数

函数参数(最好少于2个)

限制函数参数个数极其重要,这样测试你的函数容易点。有超过3个可选参数参数导致一个爆炸式组合增长,你会有成吨独立参数情形要测试。

无参数是理想情况。1个或2个都可以,最好避免3个。再多就需要加固了。通常如果你的函数有超过两个参数,说明他要处理的事太多了。 如果必须要传入很多数据,建议封装一个高级别对象作为参数。

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

好:
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 emailClients(array $clients): void
{
    foreach ($clients as $client) {
        $clientRecord = $db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
}

好:

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

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

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

函数名应体现他做了什么事

坏:
class Email
{
    //...
    public function handle(): void
    {
        mail($this->to, $this->subject, $this->body);
    }
}
$message = new Email(...);
// 啥?handle处理一个消息干嘛了?是往一个文件里写吗?
$message->handle();

好:
class Email
{
    //...
    public function send(): void
    {
        mail($this->to, $this->subject, $this->body);
    }
}
$message = new Email(...);
// 简单明了
$message->send();

函数里应当只有一层抽象abstraction

当你抽象层次过多时时,函数处理的事情太多了。需要拆分功能来提高可重用性和易用性,以便简化测试。 (从示例代码看应该是指嵌套过多)

坏:
function parseBetterJSAlternative(string $code): void
{
    $regexes = [
        // ...
    ];
    $statements = explode(' ', $code);
    $tokens = [];
    foreach ($regexes as $regex) {
        foreach ($statements as $statement) {
            // ...
        }
    }
    $ast = [];
    foreach ($tokens as $token) {
        // lex...
    }
    foreach ($ast as $node) {
        // parse...
    }
}

坏:
我们把一些方法从循环中提取出来,但是parseBetterJSAlternative()方法还是很复杂,而且不利于测试。
function tokenize(string $code): array
{
    $regexes = [
        // ...
    ];
    $statements = explode(' ', $code);
    $tokens = [];
    foreach ($regexes as $regex) {
        foreach ($statements as $statement) {
            $tokens[] = /* ... */;
        }
    }
    return $tokens;
}
function lexer(array $tokens): array
{
    $ast = [];
    foreach ($tokens as $token) {
        $ast[] = /* ... */;
    }
    return $ast;
}
function parseBetterJSAlternative(string $code): void
{
    $tokens = tokenize($code);
    $ast = lexer($tokens);
    foreach ($ast as $node) {
        // 解析逻辑...
    }
}

好:
最好的解决方案是把 parseBetterJSAlternative()方法的依赖移除。
class Tokenizer
{
    public function tokenize(string $code): array
    {
        $regexes = [
            // ...
        ];
        $statements = explode(' ', $code);
        $tokens = [];
        foreach ($regexes as $regex) {
            foreach ($statements as $statement) {
                $tokens[] = /* ... */;
            }
        }
        return $tokens;
    }
}

 
class Lexer
{
    public function lexify(array $tokens): array
    {
        $ast = [];
        foreach ($tokens as $token) {
            $ast[] = /* ... */;
        }
        return $ast;
    }
}

 
class BetterJSAlternative
{
    private $tokenizer;
    private $lexer;
    public function __construct(Tokenizer $tokenizer, Lexer $lexer)
    {
        $this->tokenizer = $tokenizer;
        $this->lexer = $lexer;
    }

    public function parse(string $code): void
    {
        $tokens = $this->tokenizer->tokenize($code);
        $ast = $this->lexer->lexify($tokens);
        foreach ($ast as $node) {
            // 解析逻辑...
        }
    }
}

这样我们可以对依赖做mock,并测试BetterJSAlternative::parse()运行是否符合预期。

不要用flag作为函数的参数

flag就是在告诉大家,这个方法里处理很多事。前面刚说过,一个函数应当只做一件事。 把不同flag的代码拆分到多个函数里。

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

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

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

避免副作用

一个函数做了比获取一个值然后返回另外一个值或值们会产生副作用如果。副作用可能是写入一个文件,修改某些全局变量或者偶然的把你全部的钱给了陌生人。

现在,你的确需要在一个程序或者场合里要有副作用,像之前的例子,你也许需要写一个文件。你想要做的是把你做这些的地方集中起来。不要用几个函数和类来写入一个特定的文件。用一个服务来做它,一个只有一个。

重点是避免常见陷阱比如对象间共享无结构的数据,使用可以写入任何的可变数据类型,不集中处理副作用发生的地方。如果你做了这些你就会比大多数程序员快乐。

坏:
// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
$name = 'Ryan McDermott';
function splitIntoFirstAndLastName(): void
{
    global $name;
    $name = explode(' ', $name);
}
splitIntoFirstAndLastName();
var_dump($name); // ['Ryan', 'McDermott'];

好:
function splitIntoFirstAndLastName(string $name): array
{
    return explode(' ', $name);
}
$name = 'Ryan McDermott';
$newName = splitIntoFirstAndLastName($name);
var_dump($name); // 'Ryan McDermott';
var_dump($newName); // ['Ryan', 'McDermott'];

不要写全局函数

在大多数语言中污染全局变量是一个坏的实践,因为你可能和其他类库冲突 并且调用你api的人直到他们捕获异常才知道踩坑了。让我们思考一种场景: 如果你想配置一个数组,你可能会写一个全局函数config(),但是他可能 和试着做同样事的其他类库冲突。

坏:
function config(): array
{
    return  [
        'foo' => 'bar',
    ]
}

好:
class Configuration
{
    private $configuration = [];
    public function __construct(array $configuration)
    {
        $this->configuration = $configuration;
    }

    public function get(string $key): ?string
    {
        return isset($this->configuration[$key]) ? $this->configuration[$key] : null;
    }
}

加载配置并创建 Configuration 类的实例
$configuration = new Configuration([
    'foo' => 'bar',
]);

现在你必须在程序中用 Configuration 的实例了

封装条件语句

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

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

避免用反义条件判断

坏:
function isDOMNodeNotPresent(\DOMNode $node): bool
{
    // ...
}

if (!isDOMNodeNotPresent($node))
{
    // ...
}

好:
function isDOMNodePresent(\DOMNode $node): bool
{
    // ...
}

if (isDOMNodePresent($node)) {
    // ...
}

避免条件判断

这看起来像一个不可能任务。当人们第一次听到这句话是都会这么说。 "没有if语句我还能做啥?" 答案是你可以使用多态来实现多种场景 的相同任务。第二个问题很常见, “这么做可以,但为什么我要这么做?” 答案是前面我们学过的一个Clean Code原则:一个函数应当只做一件事。 当你有很多含有if语句的类和函数时,你的函数做了不止一件事。 记住,只做一件事。

坏:
class Airplane
{
    // ...
    public function getCruisingAltitude(): int
    {
        switch ($this->type) {
            case '777':
                return $this->getMaxAltitude() - $this->getPassengerCount();
            case 'Air Force One':
                return $this->getMaxAltitude();
            case 'Cessna':
                return $this->getMaxAltitude() - $this->getFuelExpenditure();
        }
    }
}

好:
interface Airplane
{
    // ...
    public function getCruisingAltitude(): int;
}

class Boeing777 implements Airplane
{
    // ...
    public function getCruisingAltitude(): int
    {
        return $this->getMaxAltitude() - $this->getPassengerCount();
    }
}

class AirForceOne implements Airplane
{
    // ...
    public function getCruisingAltitude(): int
    {
        return $this->getMaxAltitude();
    }
}

class Cessna implements Airplane
{
    // ...
    public function getCruisingAltitude(): int
    {
        return $this->getMaxAltitude() - $this->getFuelExpenditure();
    }
}

避免类型检查 (part 1)

PHP是弱类型的,这意味着你的函数可以接收任何类型的参数。 有时候你为这自由所痛苦并且在你的函数渐渐尝试类型检查。 有很多方法去避免这么做。第一种是统一API。

坏:
function travelToTexas($vehicle): void
{
    if ($vehicle instanceof Bicycle) {
        $vehicle->pedalTo(new Location('texas'));
    } elseif ($vehicle instanceof Car) {
        $vehicle->driveTo(new Location('texas'));
    }
}

好:
function travelToTexas(Traveler $vehicle): void
{
    $vehicle->travelTo(new Location('texas'));
}

避免类型检查 (part 2)

如果你正使用基本原始值比如字符串、整形和数组,要求版本是PHP 7+,不用多态,需要类型检测, 那你应当考虑类型声明或者严格模式。 提供了基于标准PHP语法的静态类型。 手动检查类型的问题是做好了需要好多的废话,好像为了安全就可以不顾损失可读性。 保持你的PHP 整洁,写好测试,做好代码回顾。做不到就用PHP严格类型声明和严格模式来确保安全。

坏:
function combine($val1, $val2): int
{
    if (!is_numeric($val1) || !is_numeric($val2)) {
        throw new \Exception('Must be of type Number');
    }
    return $val1 + $val2;
}

好:
function combine(int $val1, int $val2): int
{
    return $val1 + $val2;
}

移除僵尸代码

僵尸代码和重复代码一样坏。没有理由保留在你的代码库中。如果从来没被调用过,就删掉! 因为还在代码版本库里,因此很安全。

坏:
function oldRequestModule(string $url): void
{
    // ...
}
function newRequestModule(string $url): void
{
    // ...
}
$request = newRequestModule($requestUrl);
inventoryTracker('apples', $request, 'www.inventory-awesome.io');

好:
function requestModule(string $url): void
{
    // ...
}
$request = requestModule($requestUrl);
inventoryTracker('apples', $request, 'www.inventory-awesome.io');

对象和数据结构

使用 getters 和 setters

在PHP中你可以对方法使用public, protected, private 来控制对象属性的变更。

当你想对对象属性做获取之外的操作时,你不需要在代码中去寻找并修改每一个该属性访问方法

当有set对应的属性方法时,易于增加参数的验证

封装内部的表示

使用set和get时,易于增加日志和错误控制

继承当前类时,可以复写默认的方法功能

当对象属性是从远端服务器获取时,get*,set*易于使用延迟加载

坏:
class BankAccount
{
    public $balance = 1000;
}
$bankAccount = new BankAccount();
// Buy shoes...
$bankAccount->balance -= 100;

好:
class BankAccount
{
    private $balance;
    public function __construct(int $balance = 1000)
    {
      $this->balance = $balance;
    }
    public function withdraw(int $amount): void
    {
        if ($amount > $this->balance) {
            throw new \Exception('Amount greater than available balance.');
        }
        $this->balance -= $amount;
    }
    public function deposit(int $amount): void
    {
        $this->balance += $amount;
    }
    public function getBalance(): int
    {
        return $this->balance;
    }
}
$bankAccount = new BankAccount();
// Buy shoes...
$bankAccount->withdraw($shoesPrice);
// Get balance
$balance = $bankAccount->getBalance();

给对象使用私有或受保护的成员变量

l  对public方法和属性进行修改非常危险,因为外部代码容易依赖他,而你没办法控制。对之修改影响所有这个类的使用者。 public methods and properties are most dangerous for changes, because some outside code may easily rely on them and you can't control what code relies on them. Modifications in class are dangerous for all users of class.

l  对protected的修改跟对public修改差不多危险,因为他们对子类可用,他俩的唯一区别就是可调用的位置不一样,对之修改影响所有集成这个类的地方。 protected modifier are as dangerous as public, because they are available in scope of any child class. This effectively means that difference between public and protected is only in access mechanism, but encapsulation guarantee remains the same. Modifications in class are dangerous for all descendant classes.

l  对private的修改保证了这部分代码只会影响当前类private modifier guarantees that code is dangerous to modify only in boundaries of single class (you are safe for modifications and you won't have Jenga effect).

所以,当你需要控制类里的代码可以被访问时才用public/protected,其他时候都用private。

坏:
class Employee
{
    public $name;
    public function __construct(string $name)
    {

        $this->name = $name;
    }
}
$employee = new Employee('John Doe');

echo 'Employee name: '.$employee->name; // Employee name: John Doe

好:
class Employee
{
    private $name;
    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }
}
$employee = new Employee('John Doe');
echo 'Employee name: '.$employee->getName(); // Employee name: John Doe

少用继承多用组合

正如 the Gang of Four 所著的设计模式之前所说, 我们应该尽量优先选择组合而不是继承的方式。使用继承和组合都有很多好处。 这个准则的主要意义在于当你本能的使用继承时,试着思考一下组合是否能更好对你的需求建模。 在一些情况下,是这样的。

接下来你或许会想,“那我应该在什么时候使用继承?” 答案依赖于你的问题,当然下面有一些何时继承比组合更好的说明:

  1. 你的继承表达了“是一个”而不是“有一个”的关系(人类-》动物,用户-》用户详情)
  2. 你可以复用基类的代码(人类可以像动物一样移动)
  3. 你想通过修改基类对所有派生类做全局的修改(当动物移动时,修改她们的能量消耗)
糟糕的:
 
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php 自定义验证器一:了解原始原始结构发布时间:2022-07-10
下一篇:
Android 上传图片并添加参数 PHP接收发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap