Legacy PHP: Difference between revisions

From Rixort Wiki
Jump to navigation Jump to search
Line 7: Line 7:


<code>Vendor\Package_Name\Class_Name</code> maps to: <code>Vendor/Package_Name/Class/Name.php</code>
<code>Vendor\Package_Name\Class_Name</code> maps to: <code>Vendor/Package_Name/Class/Name.php</code>
== 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 <code>Example_My_Class</code> via including <code>Example_My_Class.php</code>, which in turn includes <code>Example/My/Class.php</code>. Once every file has been migrated to autoloading, <code>Example_My_Class.php</code> can be removed.


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

Revision as of 19:59, 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.