2024-12-04

关注点分离 (SoC)

关注点分离 (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中文网其它相关文章!

https://www.php.cn/faq/1126730.html

发表回复

Your email address will not be published. Required fields are marked *