首页 > 后端开发 > 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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板