<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                [TOC] > [參考網址]( https://laravel-china.org/topics/7774/the-conciseness-of-the-php-code-php-clean-code) > PHP版本>7.1.* ## 變量 ### 正則 一般: ``` $address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); list(, $city, $zipCode) = $matches; saveCityZipCode($city, $zipCode); ``` 很棒: ``` $address = 'One Infinite Loop, Cupertino 95014'; $cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/'; preg_match($cityZipCodeRegex, $address, $matches); saveCityZipCode($matches['city'], $matches['zipCode']); ``` ### 避免嵌套太深 寫執行報錯 不好: ``` 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); } ``` ### 不要增加不需要的上下文 小壞壞: ``` 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 { // ... } ``` 好的做法: 類型提示 而且可以**保證 $breweryName 不會為空 NULL.** ``` function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void { // ... } ``` ## 函數 ### 函數參數(2 個或更少) 不友好的: ``` 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(); } ``` ### 不要使用單例模式 單例模式是個 反模式。 以下轉述 Brian Button 的觀點: 1. 單例模式常用于 全局實例, 這么做為什么不好呢? 因為在你的代碼里 你隱藏了應用的依賴關系,而沒有通過接口公開依賴關系 。避免全局的東西擴散使用是一種代碼味道. 3. 單例模式違反了 單一責任原則: 依據的事實就是 單例模式自己控制自身的創建和生命周期. 4. 單例模式天生就導致代碼緊 耦合。這使得在許多情況下用偽造的數據 難于測試。 5. 單例模式的狀態會留存于應用的整個生命周期。 這會對測試產生第二次打擊,你只能讓被嚴令需要測試的代碼運行不了收場,根本**不能進行單元測試**。為何?因為每一個單元測試應該彼此獨立。 ### 封裝條件語句 不友好的: ``` if ($article->state === 'published') { // ... } ``` 友好的: ``` if ($article->isPublished()) { // ... } ``` ### 避免使用條件語句 不好的: ``` 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(); } } ``` ## 對象和數據結構 ### 使用對象封裝 使用對象封裝,而不是直接對屬性值進行操作 不好的: ``` 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(); ``` ## 類 ## 組合優于繼承(類綁定到類屬性) > 我們應該盡量優先選擇組合而不是繼承的方式。使用繼承和組合都有很多好處。 這個準則的主要意義在于當你本能的使用繼承時,試著思考一下組合是否能更好對你的需求建模。 何時繼承比組合更好的說明: 1. 你的繼承表達了“是一個”而不是“有一個”的關系(例如人類“是”動物,而用戶“有”用戶詳情。 2. 你可以復用基類的代碼(人類可以像動物一樣移動)。 3. 你想通過修改基類對所有派生類做全局的修改(當動物移動時,修改它們的能量消耗)。 糟糕的: ``` class Employee { private $name; private $email; public function __construct(string $name, string $email){ $this->name = $name; $this->email = $email; } // ... } // 不好,因為Employees "有" taxdata // 而EmployeeTaxData不是Employee類型的 class EmployeeTaxData extends Employee { private $ssn; private $salary; public function __construct(string $name, string $email, string $ssn, string $salary){ parent::__construct($name, $email); $this->ssn = $ssn; $this->salary = $salary; } } ``` 棒棒噠: ``` class EmployeeTaxData{ private $ssn; private $salary; public function __construct(string $ssn, string $salary){ $this->ssn = $ssn; $this->salary = $salary; } } class Employee{ private $name; private $email; private $taxData; public function __construct(string $name, string $email) { $this->name = $name; $this->email = $email; } public function setTaxData(string $ssn, string $salary) { $this->taxData = new EmployeeTaxData($ssn, $salary); } } ``` ### 避免流式接口 既避免鏈式調用, 如tp中 `D("dmeo")->where([])->find();` ### 別寫重復代碼 (DRY)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看