首頁 > 後端開發 > php教程 > 關注點分離 (SoC)

關注點分離 (SoC)

Barbara Streisand
發布: 2024-12-07 07:52:17
原創
872 人瀏覽過

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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板