首页 > 后端开发 > php教程 > 关注点分离 (SoC)

关注点分离 (SoC)

Barbara Streisand
发布: 2024-12-07 07:52:17
原创
911 人浏览过

Separation of Concerns (SoC)

关键实施示例

1. 数据库层分离

// Bad - Mixed concerns
class User {
    public function save() {
        $db = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
        $stmt = $db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$this->name, $this->email]);
    }
}

// Good - Separated database logic
class User {
    private string $name;
    private string $email;
}

class UserRepository {
    private PDO $db;

    public function save(User $user) {
        $stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$user->getName(), $user->getEmail()]);
    }
}
登录后复制

这个很好的例子将数据结构(User)与存储逻辑(UserRepository)分开。这使得代码更易于维护,并且允许在不修改 User 类的情况下更改存储方法。

2. 验证分离

// Bad - Mixed validation and business logic
class Order {
    public function process() {
        if (empty($this->items)) {
            throw new Exception('Order cannot be empty');
        }
        if ($this->total < 0) {
            throw new Exception('Invalid total amount');
        }
        // Process order...
    }
}

// Good - Separated validation
class OrderValidator {
    public function validate(Order $order): array {
        $errors = [];
        if (empty($order->getItems())) {
            $errors[] = 'Order cannot be empty';
        }
        if ($order->getTotal() < 0) {
            $errors[] = 'Invalid total amount';
        }
        return $errors;
    }
}

class Order {
    public function process() {
        // Only handles order processing
    }
}
登录后复制

验证逻辑移至专用验证器类,使 Order 类能够专注于业务逻辑。

3.视图/模板分离

// Bad - Mixed HTML and logic
class ProductPage {
    public function show($id) {
        $product = $this->getProduct($id);
        echo "<h1>{$product->name}</h1>";
        echo "<p>Price: ${$product->price}</p>";
    }
}

// Good - Separated presentation
class ProductController {
    public function show($id) {
        $product = $this->productRepository->find($id);
        return $this->view->render('product/show', ['product' => $product]);
    }
}

// product/show.php template
<h1><?= htmlspecialchars($product->name) ?></h1>
<p>Price: $<?= htmlspecialchars($product->price) ?></p>
登录后复制

这个很好的例子将显示逻辑分离到模板中,使代码更易于维护,并允许设计人员独立工作。

4. 服务层分离

// Bad - Mixed business logic
class OrderController {
    public function checkout() {
        $order = new Order($_POST['items']);
        $payment = new Payment($_POST['card']);
        $payment->process();
        $order->updateStatus('paid');
        $email = new EmailService();
        $email->sendConfirmation($order);
    }
}

// Good - Separated services
class OrderService {
    private PaymentService $paymentService;
    private EmailService $emailService;

    public function processOrder(Order $order, PaymentData $paymentData): void {
        $this->paymentService->process($paymentData);
        $order->updateStatus('paid');
        $this->emailService->sendConfirmation($order);
    }
}

class OrderController {
    public function checkout() {
        $this->orderService->processOrder($order, $paymentData);
    }
}
登录后复制

服务层处理复杂的业务逻辑,使控制器专注于请求处理。

5、配置分离

// Bad - Hardcoded configuration
class EmailSender {
    private $host = 'smtp.example.com';
    private $port = 587;

    public function send($message) {
        // Sending logic using hardcoded values
    }
}

// Good - Separated configuration
// config/mail.php
return [
    'host' => 'smtp.example.com',
    'port' => 587
];

class EmailSender {
    private array $config;

    public function __construct(array $config) {
        $this->config = $config;
    }

    public function send($message) {
        // Sending logic using config values
    }
}
登录后复制

配置与实现分离,使代码更加灵活和可维护。无需修改代码即可更改设置。

以上是关注点分离 (SoC)的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板