To refactoring legacy PHP code, the answer is to improve the maintainability, testability and flexibility of the code through gradual improvement rather than one-time rewrite; specific practices include: 1. Follow the principle of single responsibility and split the classes that assume too many responsibilities into small classes that are only responsible for specific functions; 2. Follow the principle of opening and closing, expand functions through interfaces and polymorphic mechanisms rather than modifying the original code; 3. Follow the principle of Richter replacement to ensure that subclasses can transparently replace parent classes without changing program correctness; 4. Follow the principle of interface isolation and split the bloated interface into smaller dedicated interfaces; 5. Follow the principle of dependency inversion, and make high-level modules depend on abstraction rather than concrete implementation through dependency injection; in actual operation, tests should be written first, problem codes should be identified, and small steps should be refactored, and with the help of tool, gradually improve code quality rather than pursuing one-time perfection, and ultimately make the code easier to understand and expand.
Refactoring legacy PHP code to follow SOLID principles isn't about rewriting everything overnight—it's about making incremental, thoughtful improvements that increase maintainability, testability, and flexibility. Legacy systems often suffer from tight coupling, poor separation of concerns, and bloated classes. Applying SOLID principles helps address these issues systematically.

Here's how to approach refactoring legacy PHP code with each SOLID principle in mind:
1. Single Responsibility Principle (SRP)
A class should have only one reason to change.

In legacy PHP, you'll often find classes doing too much—handling database queries, formatting output, validating input, and managing business logic all in one file.
What to look for:

- Classes with multiple public methods doing unrelated things
- Long methods that mix data access, logic, and output
- Controllers that also handle validation or persistence
How to reflector:
- Break large classes into smaller, focused ones
- Extract validation, formatting, or data access into dedicated classes
- Use service classes to encapsulate business logic
Example:
// Before: User class doing too much class User { public function save() { /* saves to DB */ } public function sendWelcomeEmail() { /* sends email */ } public function validate() { /* validation logic */ } } // After: Separate responsibility class UserService { public function register(UserData $data) { $this->validator->validate($data); $this->userRepository->save($user); $this->emailService->sendWelcome($user); } }
This makes each class easier to test and modify independently.
2. Open/Closed Principle (OCP)
Software entities should be open for extension, but closed for modification.
Legacy code often requires changing existing code to add new features—this increases the risk of breaking something.
What to look for:
- Switch statements or if/else chains based on type
- Functions that need editing every time a new feature is added
How to reflector:
- Use interfaces and polymorphism
- Replace conditions with strategy or factory patterns
Example:
// Before: Adding a new payment method requires modifying this code function processPayment($type, $amount) { if ($type === 'paypal') { // process paypal } elseif ($type === 'stripe') { // process stripe } } // After: Extend via new classes, not modification interface PaymentProcessor { public function process(float $amount): void; } class PayPalProcessor implements PaymentProcessor { /* ... */ } class StripeProcessor implements PaymentProcessor { /* ... */ } class PaymentService { public function process(PaymentProcessor $processor, float $amount) { $processor->process($amount); } }
Now you can add new payment methods without touching existing logic.
3. Liskov Substitution Principle (LSP)
Subtypes must be substitutable for their base types.
This often gets violent when inheritance is used incorrectly in legacy code—eg, a child class overrides a parent method in a way that breaks expectations.
What to look for:
- Child classes throwing
NotImplementedException
- Methods that change behavior in unexpected ways
- Inheritance used just for code reuse, not true "is-a" relationships
How to reflector:
- Favor composition over inheritance
- Use interfaces to define contracts
- Restructuring hierarchies so derived classes don't surprise users
Example: Avoid creating a Rectangle
class and subclassing it into Square
if setting width affects height unexpectedly. Instead, use composition or separate independent classes.
4. Interface Segregation Principle (ISP)
Clients shouldn't be forced to depend on interfaces they don't use.
In legacy PHP, you might see large interfaces or base classes with many methods, forcing implementers to stub out unused ones.
What to look for:
- Interfaces with too many methods
- Classes implementing methods they don't need (eg, returning
null
or throwing exceptions)
How to reflector:
- Split large interfaces into smaller, role-based ones
- Let classes implement only what they need
Example:
// Before: One big interface interface UserManagement { public function save(); public function delete(); public function sendEmail(); public function generateReport(); } // After: Segregated interfaces interface Storable { public function save(); } interface Removable { public function delete(); } interface Mailable { public function sendEmail(); } interface Reportable { public function generateReport(); } class GuestUser implements Storage, Mailable { } class AdminUser implements Storage, Removable, Reportable { }
Now classes only depend on what they actually use.
5. Dependency Inversion Principle (DIP)
Depend on abstractions, not on concretes.
Legacy PHP often has hardcoded dependencies (eg, new Database()
inside a class), making testing and swapping implementations hard.
What to look for:
-
new
keyword used inside business logic - Hardcoded class names in methods
- Difficulty mocking dependencies in tests
How to reflector:
- Inject dependencies via constructor or method
- Use interfaces to decouple from concrete implementations
- Introduction a simple DI container if needed (even manual injection helps)
Example:
// Before: Tight coupling class UserService { private $db; public function __construct() { $this->db = new MySQLDatabase(); // hardcoded } } // After: Dependency injection class UserService { public function __construct(private DatabaseInterface $db) { } public function getUser($id) { return $this->db->fetch('users', $id); } }
Now you can inject a mock database for testing or switch to a different storage backend.
Practical Steps for Refactoring Legacy Code
You don't need to apply all SOLID principles at once. Start small:
- Write tests first (if none exist): Use integration or unit tests to pin down current behavior.
- Identify the worst offenders : Look for god classes, long methods, or high churn areas.
- Refactor in small steps : Extract methods → extract classes → introduction interfaces → invert dependencies.
- Use tools : PHPStan, Psalm, or Rector can help detect issues and automate some refactoring.
- Don't aim for perfection : Make it slightly better than before. Progress over purity.
SOLID isn't a rewrite checklist—it's a mindset. In legacy PHP, applying these principles gradually leads to code that's easier to understand, test, and extend. Start with SRP and DIP; they often give the biggest wins with the least risk.
Basically, just don't let the perfect be the enemy of the better.
The above is the detailed content of Refactoring Legacy PHP to Adhere to SOLID Principles. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color
