Legacy PHP: Difference between revisions

From Rixort Wiki
Jump to navigation Jump to search
No edit summary
Line 36: Line 36:
== Converting globals to injected dependencies ==
== 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();
  }
}


[[Category:PHP]]
[[Category:PHP]]

Revision as of 20:10, 24 March 2020

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();
  }
}