SOLID 原则
理解 PHP 中的 SOLID 原则
单一职责原则(SRP)
一个类应该只有一个改变的原因。
// Bad class User { public function saveUser($data) { /* ... */ } public function generateReport() { /* ... */ } public function sendEmail() { /* ... */ } } // Good class User { public function save($data) { /* ... */ } } class UserReportGenerator { public function generate() { /* ... */ } } class UserNotifier { public function sendEmail() { /* ... */ } }
开放/封闭原则(OCP)
软件实体应该对扩展开放,对修改关闭。
// Bad class PaymentProcessor { public function processPayment($type) { if ($type === 'credit') { // Process credit payment } elseif ($type === 'debit') { // Process debit payment } } } // Good interface PaymentMethod { public function processPayment(); } class CreditPayment implements PaymentMethod { public function processPayment() { /* ... */ } } class DebitPayment implements PaymentMethod { public function processPayment() { /* ... */ } }
里氏替换原则 (LSP)
子类型必须可以替代其基类型。
// Bad class Bird { public function fly() { /* ... */ } } class Penguin extends Bird { public function fly() { throw new Exception("Cannot fly"); } } // Good interface Flyable { public function fly(); } class Bird { public function eat() { /* ... */ } } class Sparrow extends Bird implements Flyable { public function fly() { /* ... */ } } class Penguin extends Bird { public function swim() { /* ... */ } }
接口隔离原则 (ISP)
客户端不应被迫依赖他们不使用的接口。
// Bad interface Worker { public function work(); public function eat(); public function sleep(); } // Good interface Workable { public function work(); } interface Eatable { public function eat(); } interface Sleepable { public function sleep(); } class Human implements Workable, Eatable, Sleepable { public function work() { /* ... */ } public function eat() { /* ... */ } public function sleep() { /* ... */ } } class Robot implements Workable { public function work() { /* ... */ } }
依赖倒置原则 (DIP)
高级模块不应该依赖于低级模块。两者都应该依赖于抽象。
// Bad class UserService { private MySQLDatabase $database; public function __construct() { $this->database = new MySQLDatabase(); } } // Good interface DatabaseInterface { public function query($sql); } class UserService { private DatabaseInterface $database; public function __construct(DatabaseInterface $database) { $this->database = $database; } } class MySQLDatabase implements DatabaseInterface { public function query($sql) { /* ... */ } } class PostgreSQLDatabase implements DatabaseInterface { public function query($sql) { /* ... */ } }
这些原则有助于创建可维护、灵活且强大的代码。遵循 SOLID 可让您的代码更易于测试、修改和扩展。