diff --git a/.github/workflows/coding_standard.yaml b/.github/workflows/coding_standard.yaml new file mode 100644 index 00000000..262b528b --- /dev/null +++ b/.github/workflows/coding_standard.yaml @@ -0,0 +1,21 @@ +name: Coding Standard + +on: + pull_request: null + push: null + +jobs: + coding_standard: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + # see https://github.com/shivammathur/setup-php + - uses: shivammathur/setup-php@v2 + with: + php-version: 8.0 + coverage: none + + - run: composer install --no-progress --ansi + + - run: vendor/bin/ecs check-markdown README.md --ansi diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..49c63d28 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +composer.lock +/vendor \ No newline at end of file diff --git a/.travis-build.php b/.travis-build.php deleted file mode 100644 index 93333509..00000000 --- a/.travis-build.php +++ /dev/null @@ -1,70 +0,0 @@ -setFlags(SplFileObject::DROP_NEW_LINE); - -$cliRedBackground = "\033[37;41m"; -$cliReset = "\033[0m"; -$exitStatus = 0; - -$indentationSteps = 3; -$manIndex = 0; -$linesWithSpaces = []; -$tableOfContentsStarted = null; -$currentTableOfContentsChapters = []; -$chaptersFound = []; -foreach ($readMeFile as $lineNumber => $line) { - if (preg_match('/\s$/', $line)) { - $linesWithSpaces[] = sprintf('%5s: %s', 1 + $lineNumber, $line); - } - if (preg_match('/^(?##+)\s(?.+)/', $line, $matches)) { - if (null === $tableOfContentsStarted) { - $tableOfContentsStarted = true; - continue; - } - $tableOfContentsStarted = false; - - $chaptersFound[] = sprintf('%s [%s](#%s)', - strlen($matches['depth']) === 2 - ? sprintf(' %s.', ++$manIndex) - : ' *' - , - $matches['title'], - preg_replace(['/ /', '/[^-\w]+/'], ['-', ''], strtolower($matches['title'])) - ); - } - if ($tableOfContentsStarted === true && isset($line[0])) { - $currentTableOfContentsChapters[] = $line; - } -} - -if (count($linesWithSpaces)) { - fwrite(STDERR, sprintf("${cliRedBackground}The following lines end with a space character:${cliReset}\n%s\n\n", - implode(PHP_EOL, $linesWithSpaces) - )); - $exitStatus = 1; -} - -$currentTableOfContentsChaptersFilename = __DIR__ . '/current-chapters'; -$chaptersFoundFilename = __DIR__ . '/chapters-found'; - -file_put_contents($currentTableOfContentsChaptersFilename, implode(PHP_EOL, $currentTableOfContentsChapters)); -file_put_contents($chaptersFoundFilename, implode(PHP_EOL, $chaptersFound)); - -$tableOfContentsDiff = shell_exec(sprintf('diff --unified %s %s', - escapeshellarg($currentTableOfContentsChaptersFilename), - escapeshellarg($chaptersFoundFilename) -)); - -@ unlink($currentTableOfContentsChaptersFilename); -@ unlink($chaptersFoundFilename); - -if (!empty($tableOfContentsDiff)) { - fwrite(STDERR, sprintf("${cliRedBackground}The table of contents is not aligned:${cliReset}\n%s\n\n", - $tableOfContentsDiff - )); - $exitStatus = 1; -} - -exit($exitStatus); diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e4ea3575..00000000 --- a/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: php - -sudo: false - -php: - - nightly - -script: php .travis-build.php - -notifications: - email: false diff --git a/README.md b/README.md index 4accc892..0c57115a 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,25 @@ # Clean Code PHP -## 翻译说明 - -本文由 php-cpm 基于 [yangweijie版本](https://github.com/yangweijie/clean-code-php) 的[clean-code-php](https://github.com/jupeter/clean-code-php)翻译并同步大量原文内容。 - -原文更新频率较高,我的翻译方法是直接用文本比较工具逐行对比。优先保证文字内容是最新的,再逐步提升翻译质量。 - -阅读过程中如果遇到各种链接失效、内容老旧、术语使用错误和其他翻译错误等问题,欢迎大家积极提交PR。 - -虽然很多开发者还在使用PHP5,但是本文中的大部分示例的运行环境需要PHP 7.1+。 - ## 目录 1. [介绍](#介绍) 2. [变量](#变量) * [使用见字知意的变量名](#使用见字知意的变量名) * [同一个实体要用相同的变量名](#同一个实体要用相同的变量名) - * [使用便于搜索的名称 (part 1)](#使用便于搜索的名称part-1) - * [使用便于搜索的名称 (part 2)](#使用便于搜索的名称part-2) - * [使用自解释型变量](#使用自解释型变量) + * [使用便于搜索的名称 (part 1)](#使用便于搜索的名称-part-1) + * [使用便于搜索的名称 (part 2)](#使用便于搜索的名称-part-2) * [使用自解释型变量](#使用自解释型变量) * [避免深层嵌套,尽早返回 (part 1)](#避免深层嵌套尽早返回-part-1) * [避免深层嵌套,尽早返回 (part 2)](#避免深层嵌套尽早返回-part-2) * [少用无意义的变量名](#少用无意义的变量名) - * [不要添加不必要上下文](#不要添加不必要上下文) + * [不要添加不必要上下文](#不要添加不必要上下文) 3. [表达式](#表达式) + * [使用恒等式](#使用恒等式) + * [Null合并运算符](#null合并运算符) + 4. [函数](#函数) * [合理使用参数默认值,没必要在方法里再做默认值检测](#合理使用参数默认值没必要在方法里再做默认值检测) - 3. [函数](#函数) * [函数参数(最好少于2个)](#函数参数-最好少于2个) * [函数应该只做一件事](#函数应该只做一件事) - * [函数名应该是有意义的动词(或表明具体做了什么事)](#函数名应该是有意义的动词或表明具体做了什么事) + * [函数名应体现他做了什么事](#函数名应体现他做了什么事) * [函数里应当只有一层抽象abstraction](#函数里应当只有一层抽象abstraction) * [不要用flag作为函数的参数](#不要用flag作为函数的参数) * [避免副作用](#避免副作用) @@ -40,20 +31,21 @@ * [避免类型检查 (part 1)](#避免类型检查-part-1) * [避免类型检查 (part 2)](#避免类型检查-part-2) * [移除僵尸代码](#移除僵尸代码) - 4. [对象和数据结构 Objects and Data Structures](#对象和数据结构) + 5. [对象和数据结构 Objects and Data Structures](#对象和数据结构) * [使用 getters 和 setters Use object encapsulation](#使用-getters-和-setters) - * [对象属性多使用private/protected限定](#对象属性多使用privateprotected限定) - 5. [类](#类) - * [组合优于继承](#组合优于继承) + * [给对象使用私有或受保护的成员变量](#给对象使用私有或受保护的成员变量) + 6. [类](#类) + * [少用继承多用组合](#少用继承多用组合) * [避免连贯接口](#避免连贯接口) - 6. [类的SOLID原则 SOLID](#solid) - * [S: 职责单一原则 Single Responsibility Principle (SRP)](#职责单一原则-single-responsibility-principle-srp) - * [O: 开闭原则 Open/Closed Principle (OCP)](#开闭原则-openclosed-principle-ocp) - * [L: 里氏替换原则 Liskov Substitution Principle (LSP)](#里氏替换原则-liskov-substitution-principle-lsp) - * [I: 接口隔离原则 Interface Segregation Principle (ISP)](#接口隔离原则-interface-segregation-principle-isp) - * [D: 依赖反转原则 Dependency Inversion Principle (DIP)](#依赖反转原则-dependency-inversion-principle-dip) - 7. [别写重复代码 (DRY)](#别写重复代码-dry) - 8. [翻译](#翻译) + * [推荐使用 final 类](#推荐使用-final-类) + 7. [类的SOLID原则 SOLID](#solid) + * [S: 单一职责原则 Single Responsibility Principle (SRP)](#单一职责原则) + * [O: 开闭原则 Open/Closed Principle (OCP)](#开闭原则) + * [L: 里氏替换原则 Liskov Substitution Principle (LSP)](#里氏替换原则) + * [I: 接口隔离原则 Interface Segregation Principle (ISP)](#接口隔离原则) + * [D: 依赖倒置原则 Dependency Inversion Principle (DIP)](#依赖倒置原则) + 8. [别写重复代码 (DRY)](#别写重复代码-dry) + 9. [翻译](#翻译) ## 介绍 @@ -65,6 +57,16 @@ 本文受到 [clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) 的启发 +虽然很多开发者还在使用PHP5,但是本文中的大部分示例的运行环境需要PHP 7.1+。 + +## 翻译说明 + +翻译完成度100%,最后更新时间2020-10-26。本文由 php-cpm 基于 [yangweijie版本](https://github.com/yangweijie/clean-code-php) 的[clean-code-php](https://github.com/jupeter/clean-code-php)翻译并同步大量原文内容。 + +原文更新频率较高,我的翻译方法是直接用文本比较工具逐行对比。优先保证文字内容是最新的,再逐步提升翻译质量。 + +阅读过程中如果遇到各种链接失效、内容老旧、术语使用错误和其他翻译错误等问题,欢迎大家积极提交PR。 + ## **变量** ### 使用见字知意的变量名 @@ -99,16 +101,18 @@ getUserProfile(); ```php getUser(); ``` + **[⬆ 返回顶部](#目录)** ### 使用便于搜索的名称 (part 1) + 写代码是用来读的。所以写出可读性高、便于搜索的代码至关重要。 命名变量时如果没有有意义、不好理解,那就是在伤害读者。 请让你的代码便于搜索。 **坏:** ```php -// What the heck is 448 for? +// 448 ™ 干啥的? $result = $serializer->serialize($data, 448); ``` @@ -118,16 +122,24 @@ $result = $serializer->serialize($data, 448); $json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ``` - ### 使用便于搜索的名称 (part 2) **坏:** ```php -// What the heck is 4 for? +class User +{ + // 7 ™ 干啥的? + public $access = 7; +} + +// 4 ™ 干啥的? if ($user->access & 4) { // ... } + +// 这里会发生什么? +$user->access ^= 2; ``` **好:** @@ -135,26 +147,35 @@ if ($user->access & 4) { ```php class User { - const ACCESS_READ = 1; - const ACCESS_CREATE = 2; -    const ACCESS_UPDATE = 4; - const ACCESS_DELETE = 8; + public const ACCESS_READ = 1; + + public const ACCESS_CREATE = 2; + + public const ACCESS_UPDATE = 4; + + public const ACCESS_DELETE = 8; + + // 默认情况下用户 具有读、写和更新权限 + public $access = self::ACCESS_READ | self::ACCESS_CREATE | self::ACCESS_UPDATE; } if ($user->access & User::ACCESS_UPDATE) { // do edit ... } + +// 禁用创建权限 +$user->access ^= User::ACCESS_CREATE; ``` **[⬆ 返回顶部](#目录)** - ### 使用自解释型变量 **坏:** + ```php $address = 'One Infinite Loop, Cupertino 95014'; -$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/'; +$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches[1], $matches[2]); @@ -166,7 +187,7 @@ saveCityZipCode($matches[1], $matches[2]); ```php $address = 'One Infinite Loop, Cupertino 95014'; -$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/'; +$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); [, $city, $zipCode] = $matches; @@ -179,7 +200,7 @@ saveCityZipCode($city, $zipCode); ```php $address = 'One Infinite Loop, Cupertino 95014'; -$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(?<city>.+?)\s*(?<zipCode>\d{5})?$/'; +$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches['city'], $matches['zipCode']); @@ -205,19 +226,16 @@ function isShopOpen($day): bool return true; } elseif ($day === 'sunday') { return true; - } else { - return false; } - } else { return false; } - } else { return false; } + return false; } ``` -**好的:** +**好:** ```php function isShopOpen(string $day): bool @@ -226,11 +244,9 @@ function isShopOpen(string $day): bool return false; } - $openingDays = [ - 'friday', 'saturday', 'sunday' - ]; + $openingDays = ['friday', 'saturday', 'sunday']; - return in_array(strtolower($day), $openingDays); + return in_array(strtolower($day), $openingDays, true); } ``` @@ -247,33 +263,26 @@ function fibonacci(int $n) if ($n !== 0) { if ($n !== 1) { return fibonacci($n - 1) + fibonacci($n - 2); - } else { - return 1; } - } else { - return 0; + return 1; } - } else { - return 'Not supported'; + return 0; } + return 'Not supported'; } ``` -**好的:** +**好:** ```php function fibonacci(int $n): int { - if ($n === 0) { - return 0; - } - - if ($n === 1) { - return 1; + if ($n === 0 || $n === 1) { + return $n; } - if ($n > 50) { - throw new \Exception('Not supported'); + if ($n >= 50) { + throw new Exception('Not supported'); } return fibonacci($n - 1) + fibonacci($n - 2); @@ -331,7 +340,9 @@ foreach ($locations as $location) { class Car { public $carMake; + public $carModel; + public $carColor; //... @@ -344,7 +355,9 @@ class Car class Car { public $make; + public $model; + public $color; //... @@ -353,11 +366,75 @@ class Car **[⬆ 返回顶部](#目录)** + +## 表达式 + +### [使用恒等式](http://php.net/manual/en/language.operators.comparison.php) + +**不好:** + +简易对比会将字符串转为整形 + +```php +$a = '42'; +$b = 42; + +if ($a != $b) { + //这里始终执行不到 +} +``` + +对比 $a != $b 返回了 `FALSE` 但应该返回 `TRUE` ! +字符串 '42' 跟整数 42 不相等 + +**好:** + +使用恒等判断检查类型和数据 + +```php +$a = '42'; +$b = 42; + +if ($a !== $b) { + // The expression is verified +} +``` + +The comparison `$a !== $b` returns `TRUE`. + +**[⬆ 返回顶部](#目录)** + +### Null合并运算符 + +Null合并运算符是 [PHP 7新特性](https://www.php.net/manual/en/migration70.new-features.php). Null合并运算符 `??` 是用来简化判断`isset()`的语法糖。如果第一个操作数存在且不为`null`则返回;否则返回第二个操作数。 + +**不好:** + +```php +if (isset($_GET['name'])) { + $name = $_GET['name']; +} elseif (isset($_POST['name'])) { + $name = $_POST['name']; +} else { + $name = 'nobody'; +} +``` + +**好:** +```php +$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody'; +``` + +**[⬆ 返回顶部](#目录)** + + +## 函数 + ### 合理使用参数默认值,没必要在方法里再做默认值检测 **不好:** -This is not good because `$breweryName` can be `NULL`. +不好,`$breweryName` 可能为 `NULL`. ```php function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void @@ -368,31 +445,31 @@ function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void **还行:** -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.'; + $breweryName = $name ?: 'Hipster Brew Co.'; // ... } ``` **好:** -If you support only PHP 7+, then you can use [type hinting](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) and be sure that the `$breweryName` will not be `NULL`. +如果你的程序只支持 PHP 7+, 那你可以用 [type hinting](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) 保证变量 `$breweryName` 不是 `NULL`. ```php function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void { -    // ... + // ... } ``` **[⬆ 返回顶部](#目录)** -## **函数** ### 函数参数(最好少于2个) + 限制函数参数个数极其重要,这样测试你的函数容易点。有超过3个可选参数参数导致一个爆炸式组合增长,你会有成吨独立参数情形要测试。 无参数是理想情况。1个或2个都可以,最好避免3个。再多就需要加固了。通常如果你的函数有超过两个参数,说明他要处理的事太多了。 如果必须要传入很多数据,建议封装一个高级别对象作为参数。 @@ -400,77 +477,89 @@ function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void **坏:** ```php -function createMenu(string $title, string $body, string $buttonText, bool $cancellable): void +class Questionnaire { - // ... + public function __construct( + string $firstname, + string $lastname, + string $patronymic, + string $region, + string $district, + string $city, + string $phone, + string $email + ) { + // ... + } } ``` **好:** ```php -class MenuConfig +class Name { - public $title; - public $body; - public $buttonText; - public $cancellable = false; -} + private $firstname; -$config = new MenuConfig(); -$config->title = 'Foo'; -$config->body = 'Bar'; -$config->buttonText = 'Baz'; -$config->cancellable = true; + private $lastname; -function createMenu(MenuConfig $config): void -{ - // ... -} -``` + private $patronymic; -**[⬆ 返回顶部](#目录)** + public function __construct(string $firstname, string $lastname, string $patronymic) + { + $this->firstname = $firstname; + $this->lastname = $lastname; + $this->patronymic = $patronymic; + } -### 函数应该只做一件事 -这是迄今为止软件工程里最重要的一个规则。当一个函数做超过一件事的时候,他们就难于实现、测试和理解。当你把一个函数拆分到只剩一个功能时,他们就容易被重构,然后你的代码读起来就更清晰。如果你光遵循这条规则,你就领先于大多数开发者了。 + // getters ... +} -**坏:** -```php -function emailClients(array $clients): void +class City { - foreach ($clients as $client) { - $clientRecord = $db->find($client); - if ($clientRecord->isActive()) { - email($client); - } - } -} -``` + private $region; -**好:** + private $district; -```php -function emailClients(array $clients): void -{ - $activeClients = activeClients($clients); - array_walk($activeClients, 'email'); + private $city; + + public function __construct(string $region, string $district, string $city) + { + $this->region = $region; + $this->district = $district; + $this->city = $city; + } + + // getters ... } -function activeClients(array $clients): array +class Contact { - return array_filter($clients, 'isClientActive'); + private $phone; + + private $email; + + public function __construct(string $phone, string $email) + { + $this->phone = $phone; + $this->email = $email; + } + + // getters ... } -function isClientActive(int $client): bool +class Questionnaire { - $clientRecord = $db->find($client); - - return $clientRecord->isActive(); + public function __construct(Name $name, City $city, Contact $contact) + { + // ... + } } ``` + **[⬆ 返回顶部](#目录)** -### 函数名应该是有意义的动词(或表明具体做了什么事) +### 函数名应体现他做了什么事 **坏:** @@ -486,14 +575,14 @@ class Email } $message = new Email(...); -// 啥?handle处理一个消息干嘛了?是往一个文件里写码? +// 啥?handle处理一个消息干嘛了?是往一个文件里写吗? $message->handle(); ``` **好:** ```php -class Email +class Email { //... @@ -518,7 +607,7 @@ $message->send(); **坏:** ```php -function parseBetterJSAlternative(string $code): void +function parseBetterPHPAlternative(string $code): void { $regexes = [ // ... @@ -575,19 +664,19 @@ function lexer(array $tokens): array return $ast; } -function parseBetterJSAlternative(string $code): void +function parseBetterPHPAlternative(string $code): void { $tokens = tokenize($code); $ast = lexer($tokens); foreach ($ast as $node) { - // parse... + // 解析逻辑... } } ``` **好:** -最好的解决方案是把 `parseBetterJSAlternative()`方法的依赖移除。 +最好的解决方案是把 `parseBetterPHPAlternative()`方法的依赖移除。 ```php class Tokenizer @@ -623,7 +712,7 @@ class Lexer } } -class BetterJSAlternative +class BetterPHPAlternative { private $tokenizer; private $lexer; @@ -639,18 +728,16 @@ class BetterJSAlternative $tokens = $this->tokenizer->tokenize($code); $ast = $this->lexer->lexify($tokens); foreach ($ast as $node) { - // parse... + // 解析逻辑... } } } ``` -这样我们可以对依赖做mock,并测试`BetterJSAlternative::parse()`运行是否符合预期。 - **[⬆ 返回顶部](#目录)** - ### 不要用flag作为函数的参数 + flag就是在告诉大家,这个方法里处理很多事。前面刚说过,一个函数应当只做一件事。 把不同flag的代码拆分到多个函数里。 **坏:** @@ -658,7 +745,7 @@ flag就是在告诉大家,这个方法里处理很多事。前面刚说过, function createFile(string $name, bool $temp = false): void { if ($temp) { - touch('./temp/'.$name); + touch('./temp/' . $name); } else { touch($name); } @@ -675,12 +762,13 @@ function createFile(string $name): void function createTempFile(string $name): void { - touch('./temp/'.$name); + touch('./temp/' . $name); } ``` **[⬆ 返回顶部](#目录)** ### 避免副作用 + 一个函数做了比获取一个值然后返回另外一个值或值们会产生副作用如果。副作用可能是写入一个文件,修改某些全局变量或者偶然的把你全部的钱给了陌生人。 现在,你的确需要在一个程序或者场合里要有副作用,像之前的例子,你也许需要写一个文件。你想要做的是把你做这些的地方集中起来。不要用几个函数和类来写入一个特定的文件。用一个服务来做它,一个只有一个。 @@ -703,7 +791,8 @@ function splitIntoFirstAndLastName(): void splitIntoFirstAndLastName(); -var_dump($name); // ['Ryan', 'McDermott']; +var_dump($name); +// ['Ryan', 'McDermott']; ``` **好:** @@ -717,8 +806,11 @@ function splitIntoFirstAndLastName(string $name): array $name = 'Ryan McDermott'; $newName = splitIntoFirstAndLastName($name); -var_dump($name); // 'Ryan McDermott'; -var_dump($newName); // ['Ryan', 'McDermott']; +var_dump($name); +// 'Ryan McDermott'; + +var_dump($newName); +// ['Ryan', 'McDermott']; ``` **[⬆ 返回顶部](#目录)** @@ -734,9 +826,9 @@ var_dump($newName); // ['Ryan', 'McDermott']; ```php function config(): array { - return [ + return [ 'foo' => 'bar', - ] + ]; } ``` @@ -754,12 +846,13 @@ class Configuration public function get(string $key): ?string { - return isset($this->configuration[$key]) ? $this->configuration[$key] : null; + // null coalescing operator + return $this->configuration[$key] ?? null; } } ``` -Load configuration and create instance of `Configuration` class +加载配置并创建 `Configuration` 类的实例 ```php $configuration = new Configuration([ @@ -767,20 +860,19 @@ $configuration = new Configuration([ ]); ``` -And now you must use instance of `Configuration` in your application. - +现在你必须在程序中用 `Configuration` 的实例了 **[⬆ 返回顶部](#目录)** ### 不要使用单例模式 -单例是一种 [反模式](https://en.wikipedia.org/wiki/Singleton_pattern). Paraphrased from Brian Button: - 1. They are generally used as a **global instance**, why is that so bad? Because **you hide the dependencies** of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a [code smell](https://en.wikipedia.org/wiki/Code_smell). - 2. They violate the [single responsibility principle](#single-responsibility-principle-srp): by virtue of the fact that **they control their own creation and lifecycle**. - 3. They inherently cause code to be tightly [coupled](https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29). This makes faking them out under **test rather difficult** in many cases. - 4. They carry state around for the lifetime of the application. Another hit to testing since **you can end up with a situation where tests need to be ordered** which is a big no for unit tests. Why? Because each unit test should be independent from the other. +单例是一种 [反模式](https://en.wikipedia.org/wiki/Singleton_pattern). 以下是解释:Paraphrased from Brian Button: + 1. 总是被用成全局实例。They are generally used as a **global instance**, why is that so bad? Because **you hide the dependencies** of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a [code smell](https://en.wikipedia.org/wiki/Code_smell). + 2. 违反了[单一响应原则]()They violate the [single responsibility principle](#single-responsibility-principle-srp): by virtue of the fact that **they control their own creation and lifecycle**. + 3. 导致代码强耦合They inherently cause code to be tightly [coupled](https://en.wikipedia.org/wiki/Coupling_%28computer_programming%29). This makes faking them out under **test rather difficult** in many cases. + 4. 在整个程序的生命周期中始终携带状态。They carry state around for the lifetime of the application. Another hit to testing since **you can end up with a situation where tests need to be ordered** which is a big no for unit tests. Why? Because each unit test should be independent from the other. -There is also very good thoughts by [Misko Hevery](http://misko.hevery.com/about/) about the [root of problem](http://misko.hevery.com/2008/08/25/root-cause-of-singletons/). +这里有一篇非常好的讨论单例模式的[根本问题((http://misko.hevery.com/2008/08/25/root-cause-of-singletons/)的文章,是[Misko Hevery](http://misko.hevery.com/about/) 写的。 **坏:** @@ -794,7 +886,7 @@ class DBConnection // ... } - public static function getInstance(): DBConnection + public static function getInstance(): self { if (self::$instance === null) { self::$instance = new self(); @@ -819,17 +911,17 @@ class DBConnection // ... } - // ... + // ... } ``` -Create instance of `DBConnection` class and configure it with [DSN](http://php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-parameters). +创建 `DBConnection` 类的实例并通过 [DSN](http://php.net/manual/en/pdo.construct.php#refsect1-pdo.construct-parameters) 配置. ```php $connection = new DBConnection($dsn); ``` -And now you must use instance of `DBConnection` in your application. +现在你必须在程序中 使用 `DBConnection` 的实例了 **[⬆ 返回顶部](#目录)** @@ -850,6 +942,7 @@ if ($article->isPublished()) { // ... } ``` + **[⬆ 返回顶部](#目录)** ### 避免用反义条件判断 @@ -857,13 +950,12 @@ if ($article->isPublished()) { **坏:** ```php -function isDOMNodeNotPresent(\DOMNode $node): bool +function isDOMNodeNotPresent(DOMNode $node): bool { // ... } -if (!isDOMNodeNotPresent($node)) -{ +if (! isDOMNodeNotPresent($node)) { // ... } ``` @@ -871,7 +963,7 @@ if (!isDOMNodeNotPresent($node)) **好:** ```php -function isDOMNodePresent(\DOMNode $node): bool +function isDOMNodePresent(DOMNode $node): bool { // ... } @@ -978,7 +1070,7 @@ function travelToTexas($vehicle): void **好:** ```php -function travelToTexas(Traveler $vehicle): void +function travelToTexas(Vehicle $vehicle): void { $vehicle->travelTo(new Location('texas')); } @@ -987,6 +1079,7 @@ function travelToTexas(Traveler $vehicle): void **[⬆ 返回顶部](#目录)** ### 避免类型检查 (part 2) + 如果你正使用基本原始值比如字符串、整形和数组,要求版本是PHP 7+,不用多态,需要类型检测, 那你应当考虑[类型声明](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration)或者严格模式。 提供了基于标准PHP语法的静态类型。 手动检查类型的问题是做好了需要好多的废话,好像为了安全就可以不顾损失可读性。 @@ -997,8 +1090,8 @@ function travelToTexas(Traveler $vehicle): void ```php function combine($val1, $val2): int { - if (!is_numeric($val1) || !is_numeric($val2)) { - throw new \Exception('Must be of type Number'); + if (! is_numeric($val1) || ! is_numeric($val2)) { + throw new Exception('Must be of type Number'); } return $val1 + $val2; @@ -1017,6 +1110,7 @@ function combine(int $val1, int $val2): int **[⬆ 返回顶部](#目录)** ### 移除僵尸代码 + 僵尸代码和重复代码一样坏。没有理由保留在你的代码库中。如果从来没被调用过,就删掉! 因为还在代码版本库里,因此很安全。 @@ -1054,6 +1148,7 @@ inventoryTracker('apples', $request, 'www.inventory-awesome.io'); ## 对象和数据结构 ### 使用 getters 和 setters + 在PHP中你可以对方法使用`public`, `protected`, `private` 来控制对象属性的变更。 * 当你想对对象属性做获取之外的操作时,你不需要在代码中去寻找并修改每一个该属性访问方法 @@ -1063,9 +1158,9 @@ inventoryTracker('apples', $request, 'www.inventory-awesome.io'); * 继承当前类时,可以复写默认的方法功能 * 当对象属性是从远端服务器获取时,get*,set*易于使用延迟加载 -此外,这样的方式也符合OOP开发中的[开闭原则](#openclosed-principle-ocp) +此外,这样的方式也符合OOP开发中的[开闭原则](#开闭原则) -**糟糕:** +**坏:** ```php class BankAccount @@ -1091,7 +1186,7 @@ class BankAccount $this->balance = $balance; } - public function withdrawBalance(int $amount): void + public function withdraw(int $amount): void { if ($amount > $this->balance) { throw new \Exception('Amount greater than available balance.'); @@ -1100,12 +1195,12 @@ class BankAccount $this->balance -= $amount; } - public function depositBalance(int $amount): void + public function deposit(int $amount): void { $this->balance += $amount; } - public function getBalance(): int +    public function getBalance(): int { return $this->balance; } @@ -1114,7 +1209,7 @@ class BankAccount $bankAccount = new BankAccount(); // Buy shoes... -$bankAccount->withdrawBalance($shoesPrice); +$bankAccount->withdraw($shoesPrice); // Get balance $balance = $bankAccount->getBalance(); @@ -1122,10 +1217,17 @@ $balance = $bankAccount->getBalance(); **[⬆ 返回顶部](#目录)** -### 对象属性多使用private/protected限定 +### 给对象使用私有或受保护的成员变量 +* 对`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.** +* 对`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.** +* 对`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](http://www.urbandictionary.com/define.php?term=Jengaphobia&defid=2494196)). -**糟糕:** +所以,当你需要控制类里的代码可以被访问时才用`public/protected`,其他时候都用`private`。 + +可以读一读这篇 [博客文章](http://fabien.potencier.org/pragmatism-over-theory-protected-vs-private.html) ,[Fabien Potencier](https://github.com/fabpot)写的. + +**坏:** ```php class Employee @@ -1139,7 +1241,8 @@ class Employee } $employee = new Employee('John Doe'); -echo 'Employee name: '.$employee->name; // Employee name: John Doe +// Employee name: John Doe +echo 'Employee name: ' . $employee->name; ``` **好:** @@ -1161,21 +1264,24 @@ class Employee } $employee = new Employee('John Doe'); -echo 'Employee name: '.$employee->getName(); // Employee name: John Doe +// Employee name: John Doe +echo 'Employee name: ' . $employee->getName(); ``` **[⬆ 返回顶部](#目录)** ## 类 -### 组合优于继承 +### 少用继承多用组合 正如 the Gang of Four 所著的[*设计模式*](https://en.wikipedia.org/wiki/Design_Patterns)之前所说, 我们应该尽量优先选择组合而不是继承的方式。使用继承和组合都有很多好处。 这个准则的主要意义在于当你本能的使用继承时,试着思考一下`组合`是否能更好对你的需求建模。 在一些情况下,是这样的。 -接下来你或许会想,“那我应该在什么时候使用继承?” 答案依赖于你的问题,当然下面有一些何时继承比组合更好的说明: +接下来你或许会想,“那我应该在什么时候使用继承?” +答案依赖于你的问题,当然下面有一些何时继承比组合更好的说明: + 1. 你的继承表达了“是一个”而不是“有一个”的关系(人类-》动物,用户-》用户详情) 2. 你可以复用基类的代码(人类可以像动物一样移动) 3. 你想通过修改基类对所有派生类做全局的修改(当动物移动时,修改她们的能量消耗) @@ -1183,9 +1289,10 @@ echo 'Employee name: '.$employee->getName(); // Employee name: John Doe **糟糕的:** ```php -class Employee +class Employee { private $name; + private $email; public function __construct(string $name, string $email) @@ -1198,15 +1305,16 @@ class Employee } -// 不好,因为Employees "有" taxdata -// 而EmployeeTaxData不是Employee类型的 +// 不好,因为 Employees "有" taxdata +// 而 EmployeeTaxData 不是 Employee 类型的 -class EmployeeTaxData extends Employee +class EmployeeTaxData extends Employee { private $ssn; + private $salary; - + public function __construct(string $name, string $email, string $ssn, string $salary) { parent::__construct($name, $email); @@ -1222,9 +1330,10 @@ class EmployeeTaxData extends Employee **好:** ```php -class EmployeeTaxData +class EmployeeTaxData { private $ssn; + private $salary; public function __construct(string $ssn, string $salary) @@ -1236,10 +1345,12 @@ class EmployeeTaxData // ... } -class Employee +class Employee { private $name; + private $email; + private $taxData; public function __construct(string $name, string $email) @@ -1248,9 +1359,9 @@ class Employee $this->email = $email; } - public function setTaxData(string $ssn, string $salary) + public function setTaxData(EmployeeTaxData $taxData): void { - $this->taxData = new EmployeeTaxData($ssn, $salary); + $this->taxData = $taxData; } // ... @@ -1264,18 +1375,22 @@ class Employee [连贯接口Fluent interface](https://en.wikipedia.org/wiki/Fluent_interface)是一种 旨在提高面向对象编程时代码可读性的API设计模式,他基于[方法链Method chaining](https://en.wikipedia.org/wiki/Method_chaining) +有上下文的地方可以降低代码复杂度,例如[PHPUnit Mock Builder](https://phpunit.de/manual/current/en/test-doubles.html) +和[Doctrine Query Builder](http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html) +,更多的情况会带来较大代价: + While there can be some contexts, frequently builder objects, where this pattern reduces the verbosity of the code (for example the [PHPUnit Mock Builder](https://phpunit.de/manual/current/en/test-doubles.html) or the [Doctrine Query Builder](http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html)), more often it comes at some costs: -1. Breaks [Encapsulation](https://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) -2. Breaks [Decorators](https://en.wikipedia.org/wiki/Decorator_pattern) -3. Is harder to [mock](https://en.wikipedia.org/wiki/Mock_object) in a test suite -4. Makes diffs of commits harder to read +1. 破坏了 [对象封装](https://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29) +2. 破坏了 [装饰器模式](https://en.wikipedia.org/wiki/Decorator_pattern) +3. 在测试组件中不好做[mock](https://en.wikipedia.org/wiki/Mock_object) +4. 导致提交的diff不好阅读 -For more informations you can read the full [blog post](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) -on this topic written by [Marco Pivetta](https://github.com/Ocramius). +了解更多请阅读 [连贯接口为什么不好](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +,作者 [Marco Pivetta](https://github.com/Ocramius). **坏:** @@ -1283,7 +1398,9 @@ on this topic written by [Marco Pivetta](https://github.com/Ocramius). class Car { private $make = 'Honda'; + private $model = 'Accord'; + private $color = 'white'; public function setMake(string $make): self @@ -1317,10 +1434,10 @@ class Car } $car = (new Car()) - ->setColor('pink') - ->setMake('Ford') - ->setModel('F-150') - ->dump(); + ->setColor('pink') + ->setMake('Ford') + ->setModel('F-150') + ->dump(); ``` **好:** @@ -1329,7 +1446,9 @@ $car = (new Car()) class Car { private $make = 'Honda'; + private $model = 'Accord'; + private $color = 'white'; public function setMake(string $make): void @@ -1362,18 +1481,85 @@ $car->dump(); **[⬆ 返回顶部](#目录)** +### 推荐使用 final 类 + +能用时尽量使用 `final` 关键字: + +1. 阻止不受控的继承链 +2. 鼓励 [组合](#少用继承多用组合). +3. 鼓励 [单一职责模式](#单一职责模式). +4. 鼓励开发者用你的公开方法而非通过继承类获取受保护方法的访问权限. +5. 使得在不破坏使用你的类的应用的情况下修改代码成为可能. + +The only condition is that your class should implement an interface and no other public methods are defined. + +For more informations you can read [the blog post](https://ocramius.github.io/blog/when-to-declare-classes-final/) on this topic written by [Marco Pivetta (Ocramius)](https://ocramius.github.io/). + +**Bad:** + +```php +final class Car +{ + private $color; + + public function __construct($color) + { + $this->color = $color; + } + + /** + * @return string The color of the vehicle + */ + public function getColor() + { + return $this->color; + } +} +``` + +**Good:** + +```php +interface Vehicle +{ + /** + * @return string The color of the vehicle + */ + public function getColor(); +} + +final class Car implements Vehicle +{ + private $color; + + public function __construct($color) + { + $this->color = $color; + } + + public function getColor() + { + return $this->color; + } +} +``` + +**[⬆ 返回顶部](#目录)** + ## SOLID **SOLID** 是Michael Feathers推荐的便于记忆的首字母简写,它代表了Robert Martin命名的最重要的五个面对对象编码设计原则 - * [S: 职责单一原则 (SRP)](#职责单一原则-single-responsibility-principle-srp) - * [O: 开闭原则 (OCP)](#开闭原则-openclosed-principle-ocp) - * [L: 里氏替换原则 (LSP)](#里氏替换原则-liskov-substitution-principle-lsp) - * [I: 接口隔离原则 (ISP)](#接口隔离原则-interface-segregation-principle-isp) - * [D: 依赖反转原则 (DIP)](#依赖反转原则-dependency-inversion-principle-dip) + * [S: 单一职责原则 (SRP)](#职责原则) + * [O: 开闭原则 (OCP)](#开闭原则) + * [L: 里氏替换原则 (LSP)](#里氏替换原则) + * [I: 接口隔离原则 (ISP)](#接口隔离原则) + * [D: 依赖倒置原则 (DIP)](#依赖倒置原则) + +### 单一职责原则 -### 职责单一原则 Single Responsibility Principle (SRP) +Single Responsibility Principle (SRP) 正如在Clean Code所述,"修改一个类应该只为一个理由"。 人们总是易于用一堆方法塞满一个类,如同我们只能在飞机上 @@ -1412,7 +1598,7 @@ class UserSettings **好:** ```php -class UserAuth +class UserAuth { private $user; @@ -1420,19 +1606,20 @@ class UserAuth { $this->user = $user; } - + public function verifyCredentials(): bool { // ... } } -class UserSettings +class UserSettings { private $user; + private $auth; - public function __construct(User $user) + public function __construct(User $user) { $this->user = $user; $this->auth = new UserAuth($user); @@ -1449,9 +1636,11 @@ class UserSettings **[⬆ 返回顶部](#目录)** -### 开闭原则 Open/Closed Principle (OCP) +### 开闭原则 -正如Bertrand Meyer所述,"软件的工件(classes, modules, functions,等) +Open/Closed Principle (OCP) + +正如Bertrand Meyer所述,"软件的工件( classes, modules, functions 等) 应该对扩展开放,对修改关闭。" 然而这句话意味着什么呢?这个原则大体上表示你 应该允许在不改变已有代码的情况下增加新的功能 @@ -1562,7 +1751,10 @@ class HttpRequester **[⬆ 返回顶部](#目录)** -### 里氏替换原则 Liskov Substitution Principle (LSP) +### 里氏替换原则 + +Liskov Substitution Principle (LSP) + 这是一个简单的原则,却用了一个不好理解的术语。它的正式定义是 "如果S是T的子类型,那么在不改变程序原有既定属性(检查、执行 任务等)的前提下,任何T类型的对象都可以使用S类型的对象替代 @@ -1580,12 +1772,8 @@ class HttpRequester class Rectangle { protected $width = 0; - protected $height = 0; - public function render(int $area): void - { - // ... - } + protected $height = 0; public function setWidth(int $width): void { @@ -1616,45 +1804,44 @@ class Square extends Rectangle } } -function renderLargeRectangles(Rectangle $rectangles): void +function printArea(Rectangle $rectangle): void { - foreach ($rectangles as $rectangle) { - $rectangle->setWidth(4); - $rectangle->setHeight(5); - $area = $rectangle->getArea(); // BAD: Will return 25 for Square. Should be 20. - $rectangle->render($area); - } + $rectangle->setWidth(4); + $rectangle->setHeight(5); + + // BAD: Will return 25 for Square. Should be 20. + echo sprintf('%s has area %d.', get_class($rectangle), $rectangle->getArea()) . PHP_EOL; } -$rectangles = [new Rectangle(), new Rectangle(), new Square()]; -renderLargeRectangles($rectangles); +$rectangles = [new Rectangle(), new Square()]; + +foreach ($rectangles as $rectangle) { + printArea($rectangle); +} ``` **好:** -```php -abstract class Shape -{ - protected $width = 0; - protected $height = 0; +最好是将这两种四边形分别对待,用一个适合两种类型的更通用子类型来代替。 - abstract public function getArea(): int; +尽管正方形和长方形看起来很相似,但他们是不同的。 +正方形更接近菱形,而长方形更接近平行四边形。但他们不是子类型。 +尽管相似,正方形、长方形、菱形、平行四边形都是有自己属性的不同形状。 - public function render(int $area): void - { - // ... - } +```php +interface Shape +{ + public function getArea(): int; } -class Rectangle extends Shape +class Rectangle implements Shape { - public function setWidth(int $width): void - { - $this->width = $width; - } + private $width = 0; + private $height = 0; - public function setHeight(int $height): void + public function __construct(int $width, int $height) { + $this->width = $width; $this->height = $height; } @@ -1664,43 +1851,38 @@ class Rectangle extends Shape } } -class Square extends Shape +class Square implements Shape { private $length = 0; - public function setLength(int $length): void + public function __construct(int $length) { $this->length = $length; } public function getArea(): int { - return pow($this->length, 2); - } +        return $this->length ** 2; +    } } -function renderLargeRectangles(Shape $rectangles): void +function printArea(Shape $shape): void { - foreach ($rectangles as $rectangle) { - if ($rectangle instanceof Square) { - $rectangle->setLength(5); - } elseif ($rectangle instanceof Rectangle) { - $rectangle->setWidth(4); - $rectangle->setHeight(5); - } - - $area = $rectangle->getArea(); - $rectangle->render($area); - } + echo sprintf('%s has area %d.', get_class($shape), $shape->getArea()).PHP_EOL; } -$shapes = [new Rectangle(), new Rectangle(), new Square()]; -renderLargeRectangles($shapes); +$shapes = [new Rectangle(4, 5), new Square(5)]; + +foreach ($shapes as $shape) { + printArea($shape); +} ``` **[⬆ 返回顶部](#目录)** -### 接口隔离原则 Interface Segregation Principle (ISP) +### 接口隔离原则 + +Interface Segregation Principle (ISP) 接口隔离原则表示:"调用方不应该被强制依赖于他不需要的接口" @@ -1718,7 +1900,7 @@ interface Employee public function eat(): void; } -class Human implements Employee +class HumanEmployee implements Employee { public function work(): void { @@ -1731,7 +1913,7 @@ class Human implements Employee } } -class Robot implements Employee +class RobotEmployee implements Employee { public function work(): void { @@ -1764,7 +1946,7 @@ interface Employee extends Feedable, Workable { } -class Human implements Employee +class HumanEmployee implements Employee { public function work(): void { @@ -1778,7 +1960,7 @@ class Human implements Employee } // robot can only work -class Robot implements Workable +class RobotEmployee implements Workable { public function work(): void { @@ -1789,16 +1971,18 @@ class Robot implements Workable **[⬆ 返回顶部](#目录)** -### 依赖反转原则 Dependency Inversion Principle (DIP) +### 依赖倒置原则 + +Dependency Inversion Principle (DIP) 这条原则说明两个基本的要点: 1. 高阶的模块不应该依赖低阶的模块,它们都应该依赖于抽象 2. 抽象不应该依赖于实现,实现应该依赖于抽象 -这条起初看起来有点晦涩难懂,但是如果你使用过php框架(例如 Symfony),你应该见过 -依赖注入(DI)对这个概念的实现。虽然它们不是完全相通的概念,依赖倒置原则使高阶模块 -与低阶模块的实现细节和创建分离。可以使用依赖注入(DI)这种方式来实现它。更多的好处 -是它使模块之间解耦。耦合会导致你难于重构,它是一种非常糟糕的的开发模式 +这条起初看起来有点晦涩难懂,但是如果你使用过 PHP 框架(例如 Symfony),你应该见过 +依赖注入(DI),它是对这个概念的实现。虽然它们不是完全相等的概念,依赖倒置原则使高阶模块 +与低阶模块的实现细节和创建分离。可以使用依赖注入(DI)这种方式来实现它。最大的好处 +是它使模块之间解耦。耦合会导致你难于重构,它是一种非常糟糕的的开发模式。 **坏:** @@ -1894,10 +2078,10 @@ class Manager 分相同的方法,移除重复的代码意味着用一个function/module/class创 建一个能处理差异的抽象。 -正确的抽象是非常关键的,这正是为什么你必须学习遵守在[Classes](#classes)章节展开 -的SOLID原则,不合理的抽象比复制代码更糟糕,所有务必谨慎!说到这么多, -如果你能设计一个合理的抽象,实现它!不要重复,否则你会发现任何时候当你 -想修改一个逻辑时你必须修改多个地方。 +用对抽象非常关键,这正是为什么你必须学习遵守在[类](#类)章节写 +的SOLID原则,不合理的抽象比复制代码更糟糕,所以务必谨慎!说了这么多, +如果你能设计一个合理的抽象,那就这么干!别写重复代码,否则你会发现 +任何时候当你想修改一个逻辑时你必须修改多个地方。 **坏:** @@ -1908,11 +2092,7 @@ function showDeveloperList(array $developers): void $expectedSalary = $developer->calculateExpectedSalary(); $experience = $developer->getExperience(); $githubLink = $developer->getGithubLink(); - $data = [ - $expectedSalary, - $experience, - $githubLink - ]; + $data = [$expectedSalary, $experience, $githubLink]; render($data); } @@ -1924,11 +2104,7 @@ function showManagerList(array $managers): void $expectedSalary = $manager->calculateExpectedSalary(); $experience = $manager->getExperience(); $githubLink = $manager->getGithubLink(); - $data = [ - $expectedSalary, - $experience, - $githubLink - ]; + $data = [$expectedSalary, $experience, $githubLink]; render($data); } @@ -1944,11 +2120,7 @@ function showList(array $employees): void $expectedSalary = $employee->calculateExpectedSalary(); $experience = $employee->getExperience(); $githubLink = $employee->getGithubLink(); - $data = [ - $expectedSalary, - $experience, - $githubLink - ]; + $data = [$expectedSalary, $experience, $githubLink]; render($data); } @@ -1957,17 +2129,13 @@ function showList(array $employees): void **极好:** -It is better to use a compact version of the code. +最好让代码紧凑一点 ```php function showList(array $employees): void { foreach ($employees as $employee) { - render([ - $employee->calculateExpectedSalary(), - $employee->getExperience(), - $employee->getGithubLink() - ]); + render([$employee->calculateExpectedSalary(), $employee->getExperience(), $employee->getGithubLink()]); } } ``` @@ -1978,16 +2146,28 @@ function showList(array $employees): void 其他语言的翻译: -* :cn: **Chinese:** - * [yangweijie/clean-code-php](https://github.com/yangweijie/clean-code-php) +* :cn: **Chinese:** * [php-cpm/clean-code-php](https://github.com/php-cpm/clean-code-php) - * [gbcr/clean-code-php](https://github.com/gbcr/clean-code-php) * :ru: **Russian:** * [peter-gribanov/clean-code-php](https://github.com/peter-gribanov/clean-code-php) +* :es: **Spanish:** + * [fikoborquez/clean-code-php](https://github.com/fikoborquez/clean-code-php) * :brazil: **Portuguese:** * [fabioars/clean-code-php](https://github.com/fabioars/clean-code-php) * [jeanjar/clean-code-php](https://github.com/jeanjar/clean-code-php/tree/pt-br) * :thailand: **Thai:** * [panuwizzle/clean-code-php](https://github.com/panuwizzle/clean-code-php) +* :fr: **French:** + * [errorname/clean-code-php](https://github.com/errorname/clean-code-php) +* :vietnam: **Vietnamese:** + * [viethuongdev/clean-code-php](https://github.com/viethuongdev/clean-code-php) +* :kr: **Korean:** + * [yujineeee/clean-code-php](https://github.com/yujineeee/clean-code-php) +* :tr: **Turkish:** + * [anilozmen/clean-code-php](https://github.com/anilozmen/clean-code-php) +* :iran: **Persian:** + * [amirshnll/clean-code-php](https://github.com/amirshnll/clean-code-php) +* :bangladesh: **Bangla:** + * [nayeemdev/clean-code-php](https://github.com/nayeemdev/clean-code-php) **[⬆ 返回顶部](#目录)** diff --git a/composer.json b/composer.json new file mode 100644 index 00000000..9c258aa3 --- /dev/null +++ b/composer.json @@ -0,0 +1,12 @@ +{ + "name": "jupeter/clean-code-php", + "description": "Clean Code concepts adapted for PHP", + "require": { + "php": ">=7.2", + "symplify/easy-coding-standard": "^9.3" + }, + "scripts": { + "check-cs": "vendor/bin/ecs check-markdown README.md", + "fix-cs": "vendor/bin/ecs check-markdown README.md --fix" + } +} diff --git a/ecs.php b/ecs.php new file mode 100644 index 00000000..b2e209ef --- /dev/null +++ b/ecs.php @@ -0,0 +1,27 @@ +<?php + +declare(strict_types=1); + +use PhpCsFixer\Fixer\PhpTag\BlankLineAfterOpeningTagFixer; +use PhpCsFixer\Fixer\Strict\DeclareStrictTypesFixer; +use PhpCsFixer\Fixer\Strict\StrictComparisonFixer; +use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; +use Symplify\EasyCodingStandard\ValueObject\Option; +use Symplify\EasyCodingStandard\ValueObject\Set\SetList; + +return static function (ContainerConfigurator $containerConfigurator): void +{ + $containerConfigurator->import(SetList::COMMON); + $containerConfigurator->import(SetList::CLEAN_CODE); + $containerConfigurator->import(SetList::PSR_12); + $containerConfigurator->import(SetList::SYMPLIFY); + + $parameters = $containerConfigurator->parameters(); + $parameters->set(Option::PATHS, [__DIR__ . '/src', __DIR__ . '/config', __DIR__ . '/ecs.php']); + + $parameters->set(Option::SKIP, [ + BlankLineAfterOpeningTagFixer::class => null, + StrictComparisonFixer::class => null, + DeclareStrictTypesFixer::class => null, + ]); +};