Legacy PHP

From Rixort Wiki
Jump to navigation Jump to search

Move code into version control

Before making any changes, move the code into a version control system. Git is the only sensible choice nowadays, due to support and developer experience.

Automatic deployment

Although not strictly related to code, having a mechanism for automatically deploying changes (once code is in version control) will save huge amounts of time, especially as you will need to deploy frequent small changes.

Converting classes to PSR-0

PSR-0 autoloading uses file and class naming conventions to map a class to a file path.

  • Namespace separators map to directory separators.
  • Class name underscores map to directory separators.

Vendor\Package_Name\Class_Name maps to: Vendor/Package_Name/Class/Name.php

Moving to autoloaders

Easiest way to do this is to move the class name to PSR-0 and then have the original class file include the autoloaded file. This allows a gradual migration to autoloading.

For example, initial starting point:

page.php:
require_once 'Example_My_Class.php';
$my_class = new Example_My_Class();
Example_My_Class.php:
class Example_My_Class {}

Change to:

page.php 
$my_class = new Example_My_Class();
Example/My/Class.php:
class Example_My_Class.php
Example_My_Class.php
require_once 'Example/My/Class.php

Initially pages will pick up Example_My_Class via including Example_My_Class.php, which in turn includes Example/My/Class.php. Once every file has been migrated to autoloading, Example_My_Class.php can be removed.

Converting globals to injected dependencies

Instead of:

class Example {
  public function foo() {
    global $db;
    $row = $db->fetch();
  }
}

Use:

class Example {
  public function __construct($db) {
    $this->db = $db;
  }

  public function foo() {
    $row = $this->db->fetch();
  }
}

Additional steps

  • Remove use of new
  • Remove embedded SQL statements
  • Remove presentation logic (e.g. if ($user->logged_in))
  • Add a router and front controller