Separation of Concerns (SoC)
Key Implementation Examples
1. Database Layer Separation
// 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()]); } }
The good example separates data structure (User) from storage logic (UserRepository). This makes the code more maintainable and allows changing the storage method without modifying the User class.
2. Validation Separation
// 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 } }
The validation logic is moved to a dedicated validator class, allowing the Order class to focus on business logic.
3. View/Template Separation
// 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>
The good example separates display logic into templates, making the code more maintainable and allowing designers to work independently.
4. Service Layer Separation
// 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); } }
The service layer handles complex business logic, keeping the controller focused on request handling.
5. Configuration Separation
// 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 } }
Configuration is separated from the implementation, making the code more flexible and maintainable. Settings can be changed without modifying the code.
The above is the detailed content of Separation of Concerns (SoC). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
