Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

PHP Modernization with Autohand Code

Upgrade legacy PHP applications to modern PHP 8+. Transform PHP 5/7 codebases with modern frameworks and patterns using Autohand Code.

Why modernize PHP?

Modern PHP offers significant improvements over legacy versions:

  • 2-3x performance improvement with JIT compilation
  • Enhanced security features and type safety
  • Modern language features (union types, attributes, enums)
  • Better error handling and debugging capabilities
  • Improved memory management and garbage collection

PHP codebase analysis

Analyze your PHP application for modernization opportunities:

# Analyze PHP 7 codebase
autohand -p "Analyze this PHP 7.4 codebase for an upgrade to PHP 8.3; write the findings to docs/php-analysis.md"

# Analysis includes:
# - Deprecated function usage
# - Framework compatibility
# - Extension dependencies
# - Code complexity metrics

PHP version upgrade

Automatically upgrade PHP syntax and deprecated functions:

# Upgrade PHP 7.4 to 8.3
autohand --worktree php83 -p "Upgrade this codebase from PHP 7.4 to 8.3: replace deprecated functions and adopt PHP 8 features where safe"

# Key transformations:
# - Named parameters and union types
# - Match expressions and nullsafe operator
// - Attributes and enums
# - String interpolation improvements

Example transformations

// Before (PHP 7.4)
function getUserData($id) {
    $user = findUser($id);
    if ($user !== null) {
        return $user->getName();
    }
    return null;
}

// Before (PHP 7.4)
class User {
    private $name;
    private $email;
    
    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }
    
    public function getName() { return $this->name; }
    public function getEmail() { return $this->email; }
}

Becomes:

// After (PHP 8.3)
function getUserData(int $id): ?string {
    return findUser($id)?->getName();
}

// After (PHP 8.3)
class User {
    public function __construct(
        private string $name,
        private string $email
    ) {}
    
    public function getName(): string { return $this->name; }
    public function getEmail(): string { return $this->email; }
}

Framework modernization

Migrate between PHP frameworks with automated transformations:

# Migrate CodeIgniter to Laravel
autohand --worktree laravel --auto-mode "Port the CodeIgniter controllers and models to Laravel 10 using Eloquent ORM" \
  --max-iterations 30 --checkpoint-interval 5 --max-cost 20

# Migrate legacy Symfony to modern Symfony
autohand --worktree symfony6 -p "Upgrade this app from Symfony 4 to Symfony 6 using autowiring and PHP attributes"

CodeIgniter to Laravel example

// Before (CodeIgniter)
class Users extends CI_Controller {
    public function index() {
        $this->load->model('user_model');
        $data['users'] = $this->user_model->get_all();
        $this->load->view('users/index', $data);
    }
}

// After (Laravel)
class UsersController extends Controller {
    public function index(): View {
        $users = User::all();
        return view('users.index', compact('users'));
    }
}

Procedural to object-oriented migration

Transform procedural PHP into modern OOP architecture:

// Before (Procedural)
function calculate_total($items) {
    $total = 0;
    foreach ($items as $item) {
        $total += $item['price'] * $item['quantity'];
    }
    return $total;
}

function apply_tax($total, $rate) {
    return $total * (1 + $rate);
}

Becomes:

// After (OOP)
class Order {
    private array $items;
    private float $taxRate;
    
    public function __construct(array $items, float $taxRate = 0.0) {
        $this->items = $items;
        $this->taxRate = $taxRate;
    }
    
    public function calculateSubtotal(): float {
        return array_reduce($this->items, fn($total, $item) => 
            $total + $item['price'] * $item['quantity'], 0.0);
    }
    
    public function calculateTotal(): float {
        return $this->calculateSubtotal() * (1 + $this->taxRate);
    }
}

Database layer modernization

Upgrade from raw SQL to modern ORM patterns:

// Before (Raw SQL)
function getUsers($limit = 10) {
    $conn = mysqli_connect('localhost', 'user', 'pass', 'db');
    $result = mysqli_query($conn, "SELECT * FROM users LIMIT $limit");
    $users = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $users[] = $row;
    }
    return $users;
}

Becomes:

// After (Eloquent ORM)
class User extends Model {
    protected $fillable = ['name', 'email', 'created_at'];
    
    public function orders(): HasMany {
        return $this->hasMany(Order::class);
    }
    
    public function scopeActive(Builder $query): Builder {
        return $query->where('status', 'active');
    }
}

// Usage
$users = User::active()->limit(10)->get();

Testing and validation

Ensure modernization doesn’t break functionality:

# Generate tests for legacy code
autohand -p "Generate Pest characterization tests for the legacy code in ./src before the PHP 8.3 upgrade"

# Validate migration
./vendor/bin/pest

# Compare behavior
autohand -p "Compare the outputs in php7-output/ and php8-output/ and write any differences to reports/behavior-diff.md"

Generated test example

// Generated test (Pest PHP)
test('calculate_total works correctly', function () {
    $items = [
        ['price' => 10.0, 'quantity' => 2],
        ['price' => 5.0, 'quantity' => 3]
    ];
    
    $order = new Order($items, 0.1);
    
    expect($order->calculateSubtotal())->toBe(35.0);
    expect($order->calculateTotal())->toBe(38.5);
});

Security modernization

Apply modern security practices automatically:

# Apply security updates
autohand -p "Find SQL injection, XSS, CSRF, and weak password hashing issues in ./src and fix them for PHP 8.3" --patch --output security.patch
git apply --check security.patch

# Key security improvements:
# - Input validation and sanitization
# - SQL injection prevention
# - XSS protection
# - CSRF token implementation
# - Password hashing updates

Security transformation example

// Before (Insecure)
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $sql);

// After (Secure)
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);

API modernization

Transform legacy APIs to modern REST/GraphQL patterns:

# Modernize API endpoints
autohand --worktree api-v2 -p "Create v2 versions of the REST v1 endpoints with request validation rules"

# Generate API documentation
autohand -p "Write an OpenAPI spec with examples for the v2 endpoints to docs/openapi.yaml"

Best practices for PHP modernization

  • Maintain comprehensive test coverage during migration
  • Use feature flags for gradual rollout
  • Implement proper error handling and logging
  • Follow PSR standards for code consistency
  • Use dependency injection for better testability
  • Implement proper caching strategies

Success story: E-commerce platform

A retail company modernized their PHP stack:

  • Scope: 800K lines of PHP 7.2 code
  • Target: PHP 8.3 + Laravel 10 + Redis cache
  • Timeline: 9 months phased migration
  • Results: 2.8x performance improvement, 60% server cost reduction
  • Architecture: Microservices with API Gateway

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification