首頁 > 後端開發 > php教程 > DRY(不要重複自己)

DRY(不要重複自己)

Susan Sarandon
發布: 2024-12-25 02:43:22
原創
574 人瀏覽過

DRY (Don

核心理念

DRY 強調系統中的每一條知識都應該有一個單一的、明確的表示。

違反 DRY 的程式碼範例

範例 1:驗證邏輯

// WET (Write Everything Twice) Code
class User {
    public function validateUsername($username) {
        if (strlen($username) < 3 || strlen($username) > 20) {
            throw new Exception("Username must be between 3 and 20 characters");
        }
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
            throw new Exception("Username can only contain letters, numbers and underscore");
        }
    }

    public function updateUsername($username) {
        // Same validation repeated
        if (strlen($username) < 3 || strlen($username) > 20) {
            throw new Exception("Username must be between 3 and 20 characters");
        }
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
            throw new Exception("Username can only contain letters, numbers and underscore");
        }
        // Update logic
    }
}
登入後複製

乾燥溶液

class User {
    private function validateUsername($username) {
        if (strlen($username) < 3 || strlen($username) > 20) {
            throw new Exception("Username must be between 3 and 20 characters");
        }
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
            throw new Exception("Username can only contain letters, numbers and underscore");
        }
    }

    public function createUser($username) {
        $this->validateUsername($username);
        // Creation logic
    }

    public function updateUsername($username) {
        $this->validateUsername($username);
        // Update logic
    }
}
登入後複製

透過繼承實現 DRY

abstract class BaseController {
    protected function jsonResponse($data, $status = 200) {
        header('Content-Type: application/json');
        http_response_code($status);
        echo json_encode($data);
    }
}

class UserController extends BaseController {
    public function show($id) {
        $user = User::find($id);
        return $this->jsonResponse($user);
    }
}

class ProductController extends BaseController {
    public function show($id) {
        $product = Product::find($id);
        return $this->jsonResponse($product);
    }
}
登入後複製

使用 DRY 特徵

trait Loggable {
    private function log($message) {
        $timestamp = date('Y-m-d H:i:s');
        file_put_contents('log.txt', "[$timestamp] $message\n", FILE_APPEND);
    }
}

class UserService {
    use Loggable;

    public function createUser($data) {
        $this->log("Creating new user");
        // User creation logic
    }
}

class PaymentService {
    use Loggable;

    public function processPayment($amount) {
        $this->log("Processing payment: $amount");
        // Payment processing logic
    }
}
登入後複製

使用常量

class Config {
    const DEFAULT_ITEMS_PER_PAGE = 10;
    const MAX_UPLOAD_SIZE = 5242880; // 5MB
    const ALLOWED_FILE_TYPES = ['jpg', 'png', 'pdf'];
}

class FileUploadService {
    public function validateFile($file) {
        if ($file['size'] > Config::MAX_UPLOAD_SIZE) {
            throw new Exception("File too large");
        }

        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        if (!in_array($extension, Config::ALLOWED_FILE_TYPES)) {
            throw new Exception("Invalid file type");
        }
    }
}

class MediaController {
    public function index() {
        return $this->paginate(Config::DEFAULT_ITEMS_PER_PAGE);
    }
}
登入後複製

這些範例示範如何透過各種 PHP 功能(如繼承、特徵、常數和正確的方法提取)應用 DRY。目標是為程式碼庫中的任何給定功能維護單一事實來源。

以上是DRY(不要重複自己)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板