PHP 7: Maintaining and Upgrading Legacy Apps · Refactoring Legacy PHP Safely
Extract Function and Extract Class
Break up long scripts and god classes in small, verifiable steps.
Legacy PHP pages often mix SQL, business rules and HTML in one 1,000-line file. Refactor in tiny steps, running tests after each: extract function for a coherent block (give it parameters instead of relying on surrounding variables), then extract class when several functions share data. IDE automated refactorings (PhpStorm) and Rector reduce mistakes. Commit refactors separately from behavior changes.
<?php
// Before: inline in checkout.php
$total = 0;
foreach ($_SESSION['cart'] as $item) {
$total += $item['price'] * $item['qty'];
}
if ($_POST['coupon'] === 'TEN') { $total = $total * 0.9; }
// After: extracted, typed and testable
final class CartTotals
{
/** @param array<int, array{price:int, qty:int}> $items */
public static function subtotal(array $items): int
{
return array_sum(array_map(fn(array $i) => $i['price'] * $i['qty'], $items));
}
public static function applyCoupon(int $subtotal, string $coupon): int
{
return $coupon === 'TEN' ? (int) round($subtotal * 0.9) : $subtotal;
}
}
$total = CartTotals::applyCoupon(CartTotals::subtotal($_SESSION['cart']), (string) ($_POST['coupon'] ?? ''));
Common pitfalls
- Changing behavior (rounding!) while extracting — characterize first.
- Extracting functions that still read globals.
- Huge refactoring PRs that nobody can review.
Key points
- Small steps with tests after each
- Pass data as parameters
- Separate refactoring from behavior changes
Further reading: Refactoring catalog: Extract Function
Practice questions
Why separate refactoring commits from behavior changes?
Answer
Reviewers can verify a refactor is behavior-preserving, and if something breaks, it's clear which change caused it and easy to revert.
What signals that an extracted set of functions should become a class?
Answer
When several functions operate on the same data or are always called together, grouping them in a class with that data as state improves cohesion.
Open in the app to mark lessons complete, take notes and track your progress.