More than 5 years have passed since last update.
PHP: Clean Code (clean-code-php) ่ๆ่ฌ
ใใใ
- ใฏใใใซ
- ๅคๆฐ
- ้ขๆฐ
- ใชใใธใงใฏใใจใใผใฟๆง้
- ใฏใฉใน
- ๅใใใจใ็นฐใ่ฟใใช (DRY)
ใฏใใใซ
ใใฎ่จไบใฏRobert C. MartinใฎๆฌใClean CodeใใฎใฝใใใฆใงใขใจใณใธใใขใชใณใฐใฎๆณๅใPHPใซ้ฉๅใใใใใฎใงใใใใใฏในใฟใคใซใฌใคใใงใฏใใใพใใใ่ชญใฟใใใใๅๅฉ็จใใใใใใใใฆใชใใกใฏใฟใชใณใฐใใใใPHPใณใผใใๆธใใใใฎใฌใคใใงใใ
ใใใงๆใใใใใในใฆใฎๅๅใฏๅณๅฏใซๅฎใใชใใฆใฏใใใชใใใใงใฏใชใใๅฐใๅฎใใชใใฃใใจใใใงไธ่ฌใซใฏ่จฑๅฎนใใใพใใใใใพใงใฌใคใใฉใคใณใงใใใClean Codeใฎ่่ ใใกใใฟใช้ทๅนดใซๆธกใฃใฆ็ต้จใใฆใใใใจใงใใ
ใใฎ่จไบ(clean-code-php)ใฏclean-code-javascriptใซ่งฆ็บใใใพใใใ
็ฟป่จณใซใคใใฆ
ใใฎ่จไบใฏclean-code-phpใใใใฟใใใ@tadsanใ้ใซๆฅๆฌ่ชใซ่จณใใใใฎใงใใ (ๅ ใฎใชใใธใงใณใฏ
1db3e53ใงใใ)่จไบใฎ็ฟป่จณไฝๆฅญใฏ2017ๅนด9ๆ3ๆฅๆ็นใงๆชๅฎไบใงใใๅๅ็จๅบฆใพใง่จณใใพใใใ
ใใๆฐใๆฎใฃใฆใใใๆๆฅใๅพๆฅใซใฏใใพใ็ถใใ่จณใใพใใๅๆใฎ่ไฝๆจฉ่กจ่จใใใณใฉใคใปใณใน่จฑ่ซพใฏไปฅไธใฎๆใงใใ
The MIT License (MIT) Copyright (c) 2016 Ryan McDermott Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
่จณ่ ใฏๅ่ใClean Codeใใใใณ็ฟป่จณๆธใฏๆช่ชญใงใใ่จณ่ชใฏWebใงไธ่ฌใซ่ฆใใใใใฎใใใใใฏ็ฌ่ชใงๅฎใฆใใใฎใงใใ
ใพใใใใใฏ้ฃฝใใพใง็ฟป่จณ่จไบใงใใ็ด่จณใงๆๅณใฎใจใใซใใใใฎใฏๆใ่ฃใฃใฆๆ่จณใใฆใใใพใ(ๆฐใซใชใใฒใจใฏๅๆใ่ชญใใงใใ ใใ)ใใใ ใๆ็จฟ่ (@tadsan)ใฎ่ฆ่งฃใจใฏ็ฐใชใ็นใซใคใใฆใฏใๅฏ่ฝใช้ใ็ง่ฆใๅ ฅใใใๅๆใฎๆๅณใๅฏ่ฝใช้ใๆฑฒใฟใพใใใ
ๅคๆฐ
ๆๅณใใใฃใฆ็บ้ณใงใใๅคๆฐๅใซใใ
๐ :no_good_tone1:
Bad (ใ ใ)
$ymdstr = $moment->format('y-m-d');
๐ :ok_woman_tone1:
Good (ใใ)
$currentDate = $moment->format('y-m-d');
ๅใๅใฎๅคๆฐใซใฏๅใๅ่ชใๅฎใฆใ
๐ :no_good_tone1:
Bad (ใ ใ)
getUserInfo();
getClientData();
getCustomerRecord();
๐ :ok_woman_tone1:
Good (ใใ)
getUser();
ๆค็ดขใใใใๅคๆฐๅใซใใ
ใใใใใกใฏใณใผใใๆธใ็ถใใ้ใใๆธใไปฅไธใซๅจๅฒใฎใณใผใใ่ชญใใใจใซใชใใพใใใชใฎใงใใณใผใใฏ่ชญใฟใใใใๆค็ดขใใใใใใใซๆธใใใจใๅคงไบใงใใๆๅณใใคใใฟใซใใๅคๆฐๅใฏใใญใฐใฉใ ใ็่งฃใใไธใงๆฏ้ใจใชใใใฎใกใฎใก่ชญ่ ใๅฐใใใใใจใซใชใใพใใใใใใใใๅคๆฐใซใฏๆค็ดขใใใใๅๅใใคใใฆใใ ใใใ
๐ :no_good_tone1:
Bad (ใ ใ)
// 86400ใฃใฆไฝโฆ??
addExpireAt(86400);
๐ :ok_woman_tone1:
Good (ใใ)
// constใญใผใฏใผใใงใๅ
จ้จๅคงๆๅญใฎๅฎๆฐๅใงๅฎ็พฉใใ
interface DateGlobal {
const SECONDS_IN_A_DAY = 86400;
}
addExpireAt(DateGlobal::SECONDS_IN_A_DAY);
่ชฌๆ็ใชๅคๆฐๅใซใใ
๐ :no_good_tone1:
Bad: (ใ ใ)
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[1], $matches[2]);
๐ :thinking:
Not bad: (ๆชใใฏใชใ)
ใใฃใใใ่ฏใใงใใใใพใ ๆญฃ่ฆ่กจ็พใฎใใใ้ ๅบใซๅผทใไพๅญใใใใพใใ
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/';
preg_match($cityZipCodeRegex, $address, $matches);
list(, $city, $zipCode) = $matchers;
saveCityZipCode($city, $zipCode);
๐ :ok_woman_tone1:
Good (ใใ)
ๅๅไปใใตใใใฟใผใณใซใใใใจใงใใใ้ ๅบใซๅฝฑ้ฟใใใชใใชใฃใใฎใงใๆญฃ่ฆ่กจ็พใฎใธใฎไพๅญใๆธใใพใใใ
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,\\]+[,\\\s]+(?<city>.+?)\s*(?<zipCode>\d{5})?$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);
ใกใณใฟใซใใใใณใฐใ้ฟใใ
่งฃ่ชญใๅฟ ่ฆใซใชใใใใชใ็ฌ็นใฎๆๅณใๆใฃใๅคๆฐๅใใคใใชใใงใใ ใใใๅคๆฐใฎๆๅณใใฏใฃใใใจๆ็ขบใงใใใใจใฏใๆ้ป็ใงใใใใใ่ฏใใใจใงใใ
๐ :no_good_tone1:
Bad (ใ ใ)
$l = ['Austin', 'New York', 'San Francisco'];
for ($i = 0; $i < count($l); $i++) {
$li = $l[$i];
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// ใพใ `$li` ใๅบใฆใใใใฉโฆ ใใใฏไฝ๏ผ
dispatch($li);
}
๐ :ok_woman_tone1:
Good (ใใ)
$locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch($location);
});
ๅๅใซใณใณใใญในใใใใฃใคใใชใ
ใฏใฉใน/ใชใใธใงใฏใใฎๅๅใซๆๅณใใใใชใใใใใๅคๆฐๅใซ็นฐใ่ฟใใชใใงใใ ใใใ
๐ :no_good_tone1:
Bad (ใ ใ)
class Car
{
public $carMake;
public $carModel;
public $carColor;
//...
}
๐ :ok_woman_tone1:
Good (ใใ)
class Car
{
public $make;
public $model;
public $color;
//...
}
็ญ็ตก่ฉไพกใงใฏใชใใใใใฉใซใๅผๆฐใซใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function createMicrobrewery($name = null) {
$breweryName = $name ?: 'Hipster Brew Co.';
// ...
}
๐ :ok_woman_tone1:
Good (ใใ)
function createMicrobrewery($breweryName = 'Hipster Brew Co.') {
// ...
}
้ขๆฐ
ๅผๆฐใฏ2ใคไปฅไธใ็ๆณ
ใใฉใกใผใฟใฎๆฐใๅถ้ใใใใจใฏใ้ขๆฐใใในใใใใใใใใใใซ้่ฆใงใใ3ใคไปฅไธใซใชใใจ็ตใฟๅใ็็บใๅผใ่ตทใใใพใใใใใชใใจใในใคในใคใฎๅคใๆธกใใฆใใใใใใชใฑใผในใใในใใใชใใใฐใใใชใใชใใพใใ
ๅผๆฐใชใใฏ็ๆณ็ใงใใ1ใคใฎๅ ดๅใจ2ใคใฎๅ ดๅใฏ็นใซๅ้กใใใพใใใ3ใคใฏ้ฟใใฆใใ ใใใ4ๅไปฅไธใชใใใใใฏ้ฃ็ตใใในใใงใใๅผๆฐใ2ใคไปฅไธใฏใใใใฆใไธใคใฎ้ขๆฐใซๅคใใฎๅฆ็ใๆใกใใใงใใใใใงใชใใใฐใ้ซ็ดใชใชใใธใงใฏใใฎใกใฝใใใฏใปใจใใฉใฎๅ ดๅใซๅผๆฐใใฒใจใคใ ใๅใใฐๅๅใงใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function createMenu($title, $body, $buttonText, $cancellable) {
// ...
}
๐ :ok_woman_tone1:
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) {
// ...
}
้ขๆฐใฏใฒใจใคใฎใใจใ ใใใใ
ใใใฏใฝใใใฆใงใขใจใณใธใใขใชใณใฐใฎใชใใงใใใใฃใจใๅคงไบใชใซใผใซใงใใ้ขๆฐใๅคใใฎใใจใใใใใจใใใจใๅฎ่ฃ ใใในใใใใใฆๆๅใๆจๆธฌใใใใจใฏ้ฃใใใชใใพใใ้ขๆฐใใฒใจใคใฎใขใฏใทใงใณใ ใใซ้้ขใงใใใฐใชใใกใฏใฟใชใณใฐใฏใใฃใจ็ฐกๅใซใชใใใณใผใใฏๆด็ทดใใใพใใ
ใใฎใฌใคใใใใปใใฎ้ ็ฎใๅ้คใใใจใใฆใใใใใ ใใฏ่ฆใใฆใใใฆใใ ใใใใใใ ใใงใใปใใฎๅคงๅขใฎ้็บ่ ใฎไธๆญฉๅ ใ่กใใใจใใงใใพใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function emailClients($clients) {
foreach ($clients as $client) {
$clientRecord = $db->find($client);
if ($clientRecord->isActive()) {
email($client);
}
}
}
๐ :ok_woman_tone1:
Good (ใใ)
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();
}
ไฝใใใใฎ้ขๆฐใชใฎใใใใๅๅใซใใ
๐ :no_good_tone1:
Bad (ใ ใ)
class Email
{
//...
public function handle()
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// ใกใใปใผใธใฎใใณใใซใฃใฆใใใใฏไฝใใฃใฆใใฎโฆ? ใใกใคใซใซๆธใ่พผใใฎ?
$message->handle();
๐ :ok_woman_tone1:
Good (ใใ)
class Email
{
//...
public function send()
{
mail($this->to, $this->subject, $this->body);
}
}
$message = new Email(...);
// ้ไฟกใใใไธ็ฎ็ญ็ถใ
$message->send();
้ขๆฐใฎๆฝ่ฑกๅใฌใใซใๅใใซใใ
ๆฝ่ฑกๅใฎใฌใใซใ็ฐใชใใชใใใใฎ้ขๆฐใฏๅคใใฎใใจใใใใใใงใใ้ขๆฐใๅๅฒใใใใจใงๅๅฉ็จๆงใๅไธใใใในใใใใใใชใใพใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function parseBetterJSAlternative($code)
{
$regexes = [
// ...
];
$statements = split(' ', $code);
$tokens = [];
foreach ($regexes as $regex) {
foreach ($statements as $statement) {
// ...
}
}
$ast = [];
foreach ($tokens as $token) {
// ๅญๅฅ่งฃๆ...
}
foreach ($ast as $node) {
// ๆงๆ่งฃๆ...
}
}
๐ :no_good_tone1:
๐ :no_good_tone1:
Bad too (ใพใ ใ ใ)
ๆฉ่ฝใใใใคใๅคใซๅบใใพใใใใใใใงใใพใ parseBetterJSAlternative()ใฏ่ค้ใงใในใใใซใใใงใใ
function tokenize($code)
{
$regexes = [
// ...
];
$statements = split(' ', $code);
$tokens = [];
foreach ($regexes as $regex) {
foreach ($statements as $statement) {
$tokens[] = /* ... */;
}
}
return $tokens;
}
function lexer($tokens)
{
$ast = [];
foreach ($tokens as $token) {
$ast[] = /* ... */;
}
return $ast;
}
function parseBetterJSAlternative($code)
{
$tokens = tokenize($code);
$ast = lexer($tokens);
foreach ($ast as $node) {
// parse...
}
}
๐ :ok_woman_tone1:
Good (ใใ)
ๆ้ซใฎ่งฃๆฑบๆนๆณใฏใไพๅญใparseBetterJSAlternative()ใใๅใๅปใใใจใงใใ
class Tokenizer
{
public function tokenize($code)
{
$regexes = [
// ...
];
$statements = split(' ', $code);
$tokens = [];
foreach ($regexes as $regex) {
foreach ($statements as $statement) {
$tokens[] = /* ... */;
}
}
return $tokens;
}
}
class Lexer
{
public function lexify($tokens)
{
$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($code)
{
$tokens = $this->tokenizer->tokenize($code);
$ast = $this->lexer->lexify($tokens);
foreach ($ast as $node) {
// parse...
}
}
}
็งใใกใฏไพๅญใใขใใฏใงใใใใใซใชใฃใใฎใงใBetterJSAlternative::parse()ใ ใใใในใใงใใใใใซใชใใพใใใ
ใใฉใฐๅผๆฐใฏๅฉ็จใใชใ
ๅผๆฐใซใใฉใฐใๅใไปใใใใจใฏใ้ขๆฐใ่คๆฐใฎๅฆ็ใๆใคใใจใ็คบใใพใใ้ขๆฐใฏใฒใจใคใฎไปไบใ ใใซๅฐๅฟตใในใใงใใใใฉใฐใซใใฃใฆ็ฐใชใๅฆ็ใใใใชใใฐใใใใฏๅฅใฎ้ขๆฐใซใใฆใใ ใใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function createFile($name, $temp = false) {
if ($temp) {
touch('./temp/'.$name);
} else {
touch($name);
}
}
๐ :ok_woman_tone1:
Good (ใใ)
function createFile($name) {
touch($name);
}
function createTempFile($name) {
touch('./temp/'.$name);
}
ๅฏไฝ็จใ้ฟใใ
ใใ้ขๆฐใใๅผๆฐใๅใๅใฃใฆๅฅใฎๅคใ่ฟใใไปฅๅคใฎๅฆ็ใใใใชใใฐใใใใๅฏไฝ็จใงใใๅฏไฝ็จใจใฏใใใกใคใซๆธใ่พผใฟใใฐใญใผใใซๅคๆฐใฎๆไฝใใใใฆใใฉใใซใงใใชใใฎๅ จ่ฒก็ฃใใฉใใใฎ่ชฐใใซ้้ใใใใจใใชใฉใงใใ
ใตใคใใใฒใจใคใฎใใญใฐใฉใ ใซใใใฆใใใใคใใฎๅฏไฝ็จใๆใใใๅฟ ่ฆใใใใพใใๅใฎไพใฎใใใซใใใกใคใซใซๆธใ่พผใๅฟ ่ฆใใใใฎใใใใใพใใใใใชใใใใใใใใจใฏใใใใใใใจใใใ้็ดใใใใจใงใใใใฎใใกใคใซใซๆธใ่พผใ้ขๆฐใใฏใฉในใๅๆฃใใใชใใงใใ ใใใใฒใจใคใฎใตใผใในใซใใใใใใพใใๅฏไธใใใ ใใงใใ
ใๆง้ ไฝใงใฏใชใใชใใธใงใฏใใฎ้ใง็ถๆ ใๅ ฑๆใใใใใฉใใใใๅคๆดใใใใใใใใใใใฎใซใใฅใผใฟใใซใชใใผใฟๅใๅฉ็จใใใใใใใฆใๅฏไฝ็จใฎ่ตทใใๅฆ็ใไธ็ฎๆใซ้็ดใใชใใใจใใฃใ่ชฐใใ้ฅใ็ฝ ใ้ฟใใใใจใใงใใใฐใใใชใใฏๅคงๅคๆฐใฎใใญใฐใฉใใผใใใๅนธใใซใชใใใจใใงใใพใใ
๐ :no_good_tone1:
Bad (ใ ใ)
// ใฐใญใผใใซๅคๆฐใใใใใฎ้ขๆฐใใๅ็
งใใใ
// ใใๅใๅคๆฐๅใไฝฟ็จใใใใจใใๅฅใฎ้ขๆฐใใใฃใใใใใฎๅฆ็ใฏๅฃใใพใ
$name = 'Ryan McDermott';
function splitIntoFirstAndLastName() {
global $name;
$name = preg_split('/ /', $name);
}
splitIntoFirstAndLastName();
var_dump($name); // ['Ryan', 'McDermott'];
๐ :ok_woman_tone1:
Good (ใใ)
$name = 'Ryan McDermott';
function splitIntoFirstAndLastName($name) {
return preg_split('/ /', $name);
}
$name = 'Ryan McDermott';
$newName = splitIntoFirstAndLastName($name);
var_dump($name); // 'Ryan McDermott';
var_dump($newName); // ['Ryan', 'McDermott'];
ใฏใญใผใใซ้ขๆฐใฏๆธใใชใ
ใใชใใฎใฉใคใใฉใชใจๅฅใฎใฉใคใใฉใชใจ้ขๆฐๅใ่ก็ชใใๅฏ่ฝๆงใใใใฎใงใๆฌ็ช็ฐๅขใฎไพๅคใ่ฆใใพใงใใชใใฎใฉใคใใฉใชใฎใฆใผใถใผใๆททไนฑใใใใใจใใใใใใใใพใใ1ใใใฎใใใๆฑๆใใใใฐใญใผใใซๅๅ็ฉบ้ใฏๅคใใฎใใญใฐใฉใใณใฐ่จ่ชใงๆชใ็ฟๆ ฃใจใใใพใใ
ไพใจใใฆใใณใณใใฃใฐใ้
ๅใจใใฆๅๅพใใใใจใใพใใconfig()ใฎใใใชใฐใญใผใใซ้
ๅใๅฎ็พฉใใใใจใใงใใพใใใๅฅใฎใฉใคใใฉใชใไผผใใใใช็ฎ็ใง่ชๅ่ช่บซใฎใณใณใใฃใฐใๅๅพใใใใใใซconfig()ใๅฎ็พฉใใใใใใใพใใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function config()
{
return [
'foo' => 'bar',
]
}
๐ :ok_woman_tone1:
Good (ใใ)
่จญๅฎใใกใคใซใ.phpใใกใคใซใจใใฆไฝๆใใพใใ
// config.php
return [
'foo' => 'bar',
];
class Configuration
{
private $configuration = [];
public function __construct(array $configuration)
{
$this->configuration = $configuration;
}
public function get($key)
{
return isset($this->configuration[$key]) ? $this->configuration[$key] : null;
}
}
ใใกใคใซใใ่จญๅฎใใญใผใใใฆใConfigurationใฏใฉในใฎใคใณในใฟใณในใไฝๆใใพใใ
$configuration = new Configuration($configuration);
ใขใใชใฑใผใทใงใณใงใฏConfigurationใฎใคใณในใฟใณในใไฝฟ็จใใๅฟ
่ฆใใใใพใใ
ใทใณใฐใซใใณใใฟใผใณใฏไฝฟ็จใใชใ
Singleton ใใฟใผใณใฏใขใณใใใฟใผใณใงใใ
๐ :no_good_tone1:
Bad (ใ ใ)
class DBConnection
{
private static $instance;
private function __construct($dsn)
{
// ...
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
// ...
}
$singleton = DBConnection::getInstance();
๐ :ok_woman_tone1:
Good (ใใ)
class DBConnection
{
public function __construct(array $dsn)
{
// ...
}
// ...
}
DBConnectionใฏใฉในใฎใคใณในใฟใณในใไฝๆใใDSNๆๅญๅใงใใใ่จญๅฎใใพใใ
$connection = new DBConnection($dsn);
ใขใใชใฑใผใทใงใณใงใฏDBConnectionใฎใคใณในใฟใณในใไฝฟ็จใใๅฟ
่ฆใใใใพใใ
ๆกไปถใใซใใปใซๅใใ
๐ :no_good_tone1:
Bad (ใ ใ)
if ($article->state === 'published') {
// ...
}
๐ :ok_woman_tone1:
Good (ใใ)
if ($article->isPublished()) {
// ...
}
้ใฎๆกไปถใ้ฟใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function isDOMNodeNotPresent($node) {
// ...
}
if (!isDOMNodeNotPresent($node)) {
// ...
}
๐ :ok_woman_tone1:
Good (ใใ)
function isDOMNodePresent($node) {
// ...
}
if (isDOMNodePresent($node)) {
// ...
}
ๆกไปถๆใ้ฟใใ
ใใใชใใจใฏไธๅฏ่ฝใชใใใซ่ฆใใพใใๆกไปถๆใ้ฟใใใจ่ใใใจใใใปใจใใฉใฎใฒใจใฏใifๆใชใใงไฝใใงใใใฎ๏ผใใจๆผใใใพใใใใฎ็ๅใธใฎๅ็ญใฏใใปใจใใฉใฎๅ ดๅใฏใใชใขใผใใฃใบใ ใงๅใใใจใใงใใใใงใใ
ๅคใใฎใฒใจใฏ็ถใใฆใใใใฏใใใใใ ใใฉใใใใใใใจไฝใใฉใใชใใฎ๏ผใใจๅฐใญใพใใใใใซๅฏพใใ็งใฎๅ็ญใฏใใใฎ่จไบใ้ใใฆๅญฆใใงใใใ้ขๆฐใฏใฒใจใคใฎใใจใ ใใใใใใงใใ่ฆใใฆใใใฆใใ ใใใใ้ขๆฐใฏใฒใจใคใฎใใจใ ใใใใใใงใใ
๐ :no_good_tone1:
Bad (ใ ใ)
class Airplane {
// ...
public function getCruisingAltitude() {
switch ($this->type) {
case '777':
return $this->getMaxAltitude() - $this->getPassengerCount();
case 'Air Force One':
return $this->getMaxAltitude();
case 'Cessna':
return $this->getMaxAltitude() - $this->getFuelExpenditure();
}
}
}
๐ :ok_woman_tone1:
Good (ใใ)
class Airplane {
// ...
}
class Boeing777 extends Airplane {
// ...
public function getCruisingAltitude() {
return $this->getMaxAltitude() - $this->getPassengerCount();
}
}
class AirForceOne extends Airplane {
// ...
public function getCruisingAltitude() {
return $this->getMaxAltitude();
}
}
class Cessna extends Airplane {
// ...
public function getCruisingAltitude() {
return $this->getMaxAltitude() - $this->getFuelExpenditure();
}
}
ๅใใงใใฏใ้ฟใใ (ใใฎ1)
PHPใฎ้ขๆฐใซใฏๅใใชใใใฉใใชๅใฎๅผๆฐใงใๅใไปใใใใจใใงใใพใใๆใซใฏใใฎ่ช็ฑใซ่ถณใๅใพใใๆใซ้ขๆฐใงๅใใงใใฏใใใ่ชๆใซ้งใใใพใใใใใใใใใ้ฟใใๆนๆณใฏใใใคใใใใพใใใฏใใใซ่ๆ ฎใในใใฏใไธ่ฒซใใAPIใงใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function travelToTexas($vehicle)
{
if ($vehicle instanceof Bicycle) {
$vehicle->peddleTo(new Location('texas'));
} elseif ($vehicle instanceof Car) {
$vehicle->driveTo(new Location('texas'));
}
}
๐ :ok_woman_tone1:
Good (ใใ)
function travelToTexas(Traveler $vehicle)
{
$vehicle->travelTo(new Location('texas'));
}
ๅใใงใใฏใ้ฟใใ (ใใฎ2)
ๆๅญๅใๆดๆฐใใใใฆ้ ๅใฎใใใชๅบๆฌ็ใชใใชใใใฃใๅคใไฝฟใฃใฆ้ขๆฐใๅฎ็พฉใใใจใใใใใใชใใPHP7ไปฅ้ใงใใใใฆใใชใขใผใใฃใบใ ใๆก็จใใใใจใฏใงใใชใใๅใใงใใฏใซ้ ผใใใใชใฃใใชใใๅๅฎฃ่จใจใๅณๅฏใชๅใใงใใฏใใขใผใใฏไธ่ใฎไฝๅฐใใใใพใใใใใฏ้ๅธธใฎPHPใฎๆงๆใฎไธใซ้็ๅไปใใ่ฟฝๅ ใใพใใ
ๆไฝๆฅญใงใฎๅใใงใใฏใฏใใใใใใพใๅไฝใใใใใใซใฏไฝๅใช่จ่ฟฐใๅฟ ่ฆใซใชใใใจใๅ้กใงใใใใใซใใฃใฆๅพใใพใใใใฎๅๅฎๅ จๆงใฏใๆใญใใใ่ชญใฟใซใใใ่ฃๅฎใงใใพใใใPHPใฎใณใผใใ็ถบ้บใซไฟใกใ่ฏใใในใใๆธใใใใใฆใใกใใจใณใผใใฌใใฅใผใใใฆใใ ใใใใใใงใชใใใฐใPHPใฎๅๅฎฃ่จใจใๅณๅฏใชๅใใงใใฏใใขใผใใๅฉ็จใใใใจใงใใใๅฎ็พใงใใพใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function combine($val1, $val2)
{
if (!is_numeric($val1) || !is_numeric($val2)) {
throw new \Exception('Must be of type Number');
}
return $val1 + $val2;
}
๐ :ok_woman_tone1:
Good (ใใ)
function combine(int $val1, int $val2)
{
return $val1 + $val2;
}
ไธ่ฆใณใผใใฏๆถใ
ใใใใณใผใ(ไธ่ฆใชใณใผใ)ใฏ้่คใณใผใใจๅใใๆชใงใใ็็ฑใใชใใฎใซใใใๆฎใใชใใงใใ ใใใใใๅผใฐใใชใใชใใๆถใๅปใฃใฆใใ ใใ๏ผ ใใๅฐๆฅๅฟ ่ฆใซใชใใ ใใใจๆใฃใฆใใใใใฏGitใชใฉใฎใใผใธใงใณ็ฎก็ใทในใใ ใฎๅฑฅๆญดใใๅฎๅ จใซๅใๅบใใใจใใงใใพใใ
๐ :no_good_tone1:
Bad (ใ ใ)
function oldRequestModule($url) {
// ...
}
function newRequestModule($url) {
// ...
}
$req = new newRequestModule($requestUrl);
inventoryTracker('apples', $req, 'www.inventory-awesome.io');
๐ :ok_woman_tone1:
Good (ใใ)
function requestModule($url) {
// ...
}
$req = new requestModule($requestUrl);
inventoryTracker('apples', $req, 'www.inventory-awesome.io');
ใใพใฎใจใใใ็ฟป่จณใฏใใใพใงใๆใใใฃใใใๆๆฅใฏๅพๆฅใซใฏ็ถใใ่จณใใพใใ
ใชใใธใงใฏใใจใใผใฟๆง้
ใฒใใฟใผใจใปใใฟใผใๅฉ็จใใ
PHPใงใฏใกใฝใใใซpublic, protected, privateใฎใญใผใฏใผใใๆๅฎใงใใพใใใใใๅฉ็จใใใใจใงใใญใใใฃใฎๅคๆดใๅถๅพกใงใใพใใ
- When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
- Makes adding validation simple when doing a
set. - Encapsulates the internal representation.
- Easy to add logging and error handling when getting and setting.
- Inheriting this class, you can override default functionality.
- You can lazy load your object's properties, let's say getting it from a
server.
Additionally, this is part of Open/Closed principle, from object-oriented
design principles.
๐ :no_good_tone1:
Bad (ใ ใ)
class BankAccount {
public $balance = 1000;
}
$bankAccount = new BankAccount();
// Buy shoes...
$bankAccount->balance -= 100;
๐ :ok_woman_tone1:
Good (ใใ)
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();
ใชใใธใงใฏใใฎใใญใใใฃใฏprivate/protectedใซใใ
๐ :no_good_tone1:
Bad (ใ ใ)
class Employee {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$employee = new Employee('John Doe');
echo 'Employee name: '.$employee->name; // Employee name: John Doe
๐ :ok_woman_tone1:
Good (ใใ)
class Employee {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$employee = new Employee('John Doe');
echo 'Employee name: '.$employee->getName(); // Employee name: John Doe
ใฏใฉใน
S: ๅไธ่ฒฌไปปใฎๅๅ (SRP)
As stated in Clean Code, "There should never be more than one reason for a class
to change". It's tempting to jam-pack a class with a lot of functionality, like
when you can only take one suitcase on your flight. The issue with this is
that your class won't be conceptually cohesive and it will give it many reasons
to change. Minimizing the amount of times you need to change a class is important.
It's important because if too much functionality is in one class and you modify a piece of it,
it can be difficult to understand how that will affect other dependent modules in
your codebase.
๐ :no_good_tone1:
Bad (ใ ใ)
class UserSettings {
private $user;
public function __construct($user) {
$this->user = user;
}
public function changeSettings($settings) {
if ($this->verifyCredentials()) {
// ...
}
}
private function verifyCredentials() {
// ...
}
}
๐ :ok_woman_tone1:
Good (ใใ)
class UserAuth {
private $user;
public function __construct($user) {
$this->user = user;
}
public function verifyCredentials() {
// ...
}
}
class UserSettings {
private $user;
public function __construct($user) {
$this->user = $user;
$this->auth = new UserAuth($user);
}
public function changeSettings($settings) {
if ($this->auth->verifyCredentials()) {
// ...
}
}
}
O: ใชใผใใณ/ใฏใญใผใบใใฎๅๅ (OCP)
As stated by Bertrand Meyer, "software entities (classes, modules, functions,
etc.) should be open for extension, but closed for modification." What does that
mean though? This principle basically states that you should allow users to
add new functionalities without changing existing code.
๐ :no_good_tone1:
Bad (ใ ใ)
abstract class Adapter
{
protected $name;
public function getName()
{
return $this->name;
}
}
class AjaxAdapter extends Adapter
{
public function __construct()
{
parent::__construct();
$this->name = 'ajaxAdapter';
}
}
class NodeAdapter extends Adapter
{
public function __construct()
{
parent::__construct();
$this->name = 'nodeAdapter';
}
}
class HttpRequester
{
private $adapter;
public function __construct($adapter)
{
$this->adapter = $adapter;
}
public function fetch($url)
{
$adapterName = $this->adapter->getName();
if ($adapterName === 'ajaxAdapter') {
return $this->makeAjaxCall($url);
} elseif ($adapterName === 'httpNodeAdapter') {
return $this->makeHttpCall($url);
}
}
protected function makeAjaxCall($url)
{
// request and return promise
}
protected function makeHttpCall($url)
{
// request and return promise
}
}
๐ :ok_woman_tone1:
Good (ใใ)
interface Adapter
{
public function request($url);
}
class AjaxAdapter implements Adapter
{
public function request($url)
{
// request and return promise
}
}
class NodeAdapter implements Adapter
{
public function request($url)
{
// request and return promise
}
}
class HttpRequester
{
private $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
public function fetch($url)
{
return $this->adapter->request($url);
}
}
L: ใชในใณใใฎ็ฝฎๆๅๅ (LSP)
This is a scary term for a very simple concept. It's formally defined as "If S
is a subtype of T, then objects of type T may be replaced with objects of type S
(i.e., objects of type S may substitute objects of type T) without altering any
of the desirable properties of that program (correctness, task performed,
etc.)." That's an even scarier definition.
The best explanation for this is if you have a parent class and a child class,
then the base class and child class can be used interchangeably without getting
incorrect results. This might still be confusing, so let's take a look at the
classic Square-Rectangle example. Mathematically, a square is a rectangle, but
if you model it using the "is-a" relationship via inheritance, you quickly
get into trouble.
๐ :no_good_tone1:
Bad (ใ ใ)
class Rectangle {
private $width, $height;
public function __construct() {
$this->width = 0;
$this->height = 0;
}
public function setColor($color) {
// ...
}
public function render($area) {
// ...
}
public function setWidth($width) {
$this->width = $width;
}
public function setHeight($height) {
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
class Square extends Rectangle {
public function setWidth($width) {
$this->width = $this->height = $width;
}
public function setHeight(height) {
$this->width = $this->height = $height;
}
}
function renderLargeRectangles($rectangles) {
foreach($rectangle in $rectangles) {
$rectangle->setWidth(4);
$rectangle->setHeight(5);
$area = $rectangle->getArea(); // BAD: Will return 25 for Square. Should be 20.
$rectangle->render($area);
});
}
$rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles($rectangles);
๐ :ok_woman_tone1:
Good (ใใ)
abstract class Shape {
private $width, $height;
abstract public function getArea();
public function setColor($color) {
// ...
}
public function render($area) {
// ...
}
}
class Rectangle extends Shape {
public function __construct {
parent::__construct();
$this->width = 0;
$this->height = 0;
}
public function setWidth($width) {
$this->width = $width;
}
public function setHeight($height) {
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
class Square extends Shape {
public function __construct {
parent::__construct();
$this->length = 0;
}
public function setLength($length) {
$this->length = $length;
}
public function getArea() {
return pow($this->length, 2);
}
}
function renderLargeRectangles($rectangles) {
foreach($rectangle in $rectangles) {
if ($rectangle instanceof Square) {
$rectangle->setLength(5);
} else if ($rectangle instanceof Rectangle) {
$rectangle->setWidth(4);
$rectangle->setHeight(5);
}
$area = $rectangle->getArea();
$rectangle->render($area);
});
}
$shapes = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles($shapes);
I: ใคใณใฟใผใใงใคในๅ้ขใฎๅๅ (ISP)
ISP states that "Clients should not be forced to depend upon interfaces that
they do not use."
A good example to look at that demonstrates this principle is for
classes that require large settings objects. Not requiring clients to setup
huge amounts of options is beneficial, because most of the time they won't need
all of the settings. Making them optional helps prevent having a "fat interface".
๐ :no_good_tone1:
Bad (ใ ใ)
interface WorkerInterface {
public function work();
public function eat();
}
class Worker implements WorkerInterface {
public function work() {
// ....working
}
public function eat() {
// ...... eating in launch break
}
}
class SuperWorker implements WorkerInterface {
public function work() {
//.... working much more
}
public function eat() {
//.... eating in launch break
}
}
class Manager {
/** @var WorkerInterface $worker **/
private $worker;
public function setWorker(WorkerInterface $worker) {
$this->worker = $worker;
}
public function manage() {
$this->worker->work();
}
}
๐ :ok_woman_tone1:
Good (ใใ)
interface WorkerInterface extends FeedableInterface, WorkableInterface {
}
interface WorkableInterface {
public function work();
}
interface FeedableInterface {
public function eat();
}
class Worker implements WorkableInterface, FeedableInterface {
public function work() {
// ....working
}
public function eat() {
//.... eating in launch break
}
}
class Robot implements WorkableInterface {
public function work() {
// ....working
}
}
class SuperWorker implements WorkerInterface {
public function work() {
//.... working much more
}
public function eat() {
//.... eating in launch break
}
}
class Manager {
/** @var $worker WorkableInterface **/
private $worker;
public function setWorker(WorkableInterface $w) {
$this->worker = $w;
}
public function manage() {
$this->worker->work();
}
}
D: ไพๅญ้่ปขใฎๆณๅ (DIP)
This principle states two essential things:
- High-level modules should not depend on low-level modules. Both should
depend on abstractions. - Abstractions should not depend upon details. Details should depend on
abstractions.
This can be hard to understand at first, but if you've worked with PHP frameworks (like Symfony), you've seen an implementation of this principle in the form of Dependency
Injection (DI). While they are not identical concepts, DIP keeps high-level
modules from knowing the details of its low-level modules and setting them up.
It can accomplish this through DI. A huge benefit of this is that it reduces
the coupling between modules. Coupling is a very bad development pattern because
it makes your code hard to refactor.
๐ :no_good_tone1:
Bad (ใ ใ)
class Worker {
public function work() {
// ....working
}
}
class Manager {
/** @var Worker $worker **/
private $worker;
public function __construct(Worker $worker) {
$this->worker = $worker;
}
public function manage() {
$this->worker->work();
}
}
class SuperWorker extends Worker {
public function work() {
//.... working much more
}
}
๐ :ok_woman_tone1:
Good (ใใ)
interface WorkerInterface {
public function work();
}
class Worker implements WorkerInterface {
public function work() {
// ....working
}
}
class SuperWorker implements WorkerInterface {
public function work() {
//.... working much more
}
}
class Manager {
/** @var Worker $worker **/
private $worker;
public function __construct(WorkerInterface $worker) {
$this->worker = $worker;
}
public function manage() {
$this->worker->work();
}
}
ใกใฝใใใใงใผใณใๅฉ็จใใ
This pattern is very useful and commonly used it many libraries such
as PHPUnit and Doctrine. It allows your code to be expressive, and less verbose.
For that reason, I say, use method chaining and take a look at how clean your code
will be. In your class functions, simply return this at the end of every function,
and you can chain further class methods onto it.
๐ :no_good_tone1:
Bad (ใ ใ)
class Car {
private $make, $model, $color;
public function __construct() {
$this->make = 'Honda';
$this->model = 'Accord';
$this->color = 'white';
}
public function setMake($make) {
$this->make = $make;
}
public function setModel($model) {
$this->model = $model;
}
public function setColor($color) {
$this->color = $color;
}
public function dump() {
var_dump($this->make, $this->model, $this->color);
}
}
$car = new Car();
$car->setColor('pink');
$car->setMake('Ford');
$car->setModel('F-150');
$car->dump();
๐ :ok_woman_tone1:
Good (ใใ)
class Car {
private $make, $model, $color;
public function __construct() {
$this->make = 'Honda';
$this->model = 'Accord';
$this->color = 'white';
}
public function setMake($make) {
$this->make = $make;
// NOTE: Returning this for chaining
return $this;
}
public function setModel($model) {
$this->model = $model;
// NOTE: Returning this for chaining
return $this;
}
public function setColor($color) {
$this->color = $color;
// NOTE: Returning this for chaining
return $this;
}
public function dump() {
var_dump($this->make, $this->model, $this->color);
}
}
$car = (new Car())
->setColor('pink')
->setMake('Ford')
->setModel('F-150')
->dump();
็ถๆฟใใใใณใณใใธใทใงใณ
As stated famously in Design Patterns by the Gang of Four,
you should prefer composition over inheritance where you can. There are lots of
good reasons to use inheritance and lots of good reasons to use composition.
The main point for this maxim is that if your mind instinctively goes for
inheritance, try to think if composition could model your problem better. In some
cases it can.
You might be wondering then, "when should I use inheritance?" It
depends on your problem at hand, but this is a decent list of when inheritance
makes more sense than composition:
- Your inheritance represents an "is-a" relationship and not a "has-a"
relationship (Human->Animal vs. User->UserDetails). - You can reuse code from the base classes (Humans can move like all animals).
- You want to make global changes to derived classes by changing a base class.
(Change the caloric expenditure of all animals when they move).
๐ :no_good_tone1:
Bad (ใ ใ)
class Employee {
private $name, $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
// ...
}
// Bad because Employees "have" tax data.
// EmployeeTaxData is not a type of Employee
class EmployeeTaxData extends Employee {
private $ssn, $salary;
public function __construct($name, $email, $ssn, $salary) {
parent::__construct($name, $email);
$this->ssn = $ssn;
$this->salary = $salary;
}
// ...
}
๐ :ok_woman_tone1:
Good (ใใ)
class EmployeeTaxData {
private $ssn, $salary;
public function __construct($ssn, $salary) {
$this->ssn = $ssn;
$this->salary = $salary;
}
// ...
}
class Employee {
private $name, $email, $taxData;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function setTaxData($ssn, $salary) {
$this->taxData = new EmployeeTaxData($ssn, $salary);
}
// ...
}
ๅใใใจใ็นฐใ่ฟใใช (DRY)
Try to observe the DRY principle.
Do your absolute best to avoid duplicate code. Duplicate code is bad because
it means that there's more than one place to alter something if you need to
change some logic.
Imagine if you run a restaurant and you keep track of your inventory: all your
tomatoes, onions, garlic, spices, etc. If you have multiple lists that
you keep this on, then all have to be updated when you serve a dish with
tomatoes in them. If you only have one list, there's only one place to update!
Oftentimes you have duplicate code because you have two or more slightly
different things, that share a lot in common, but their differences force you
to have two or more separate functions that do much of the same things. Removing
duplicate code means creating an abstraction that can handle this set of different
things with just one function/module/class.
Getting the abstraction right is critical, that's why you should follow the
SOLID principles laid out in the Classes section. Bad abstractions can be
worse than duplicate code, so be careful! Having said this, if you can make
a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself
updating multiple places anytime you want to change one thing.
๐ :no_good_tone1:
Bad (ใ ใ)
function showDeveloperList($developers)
{
foreach ($developers as $developer) {
$expectedSalary = $developer->calculateExpectedSalary();
$experience = $developer->getExperience();
$githubLink = $developer->getGithubLink();
$data = [
$expectedSalary,
$experience,
$githubLink
];
render($data);
}
}
function showManagerList($managers)
{
foreach ($managers as $manager) {
$expectedSalary = $manager->calculateExpectedSalary();
$experience = $manager->getExperience();
$githubLink = $manager->getGithubLink();
$data = [
$expectedSalary,
$experience,
$githubLink
];
render($data);
}
}
๐ :ok_woman_tone1:
Good (ใใ)
function showList($employees)
{
foreach ($employees as $employee) {
$expectedSalary = $employee->calculateExpectedSalary();
$experience = $employee->getExperience();
$githubLink = $employee->getGithubLink();
$data = [
$expectedSalary,
$experience,
$githubLink
];
render($data);
}
}
Very good:
It is better to use a compact version of the code.
function showList($employees)
{
foreach ($employees as $employee) {
render([
$employee->calculateExpectedSalary(),
$employee->getExperience(),
$employee->getGithubLink()
]);
}
}
่ๆณจ
-
่จณๆณจ: ๆฌๅฝใใโฆ๏ผ (็ฟป่จณใซ่ชไฟกใๆใฆใชใ) ๅๆใงใฏไปฅไธใฎ้ใ:
Polluting globals is a bad practice in very languages because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production.
โฉ
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
