PSR-4 Autoloader
suggest changePSR-4 is an accepted recommendation that outlines the standard for autoloading classes via filenames. This recommendation is recommended as the alternative to the earlier (and now deprecated) PSR-0.
The fully qualified class name should match the following requirement:
\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>
- It MUST contain a top level vendor namespace (E.g.:
Alphabet) - It MAY contain one or more sub-namespaces (E.g.:
Google\AdWord) - It MUST contain an ending class name (E.g.:
KeywordPlanner)
Thus the final class name would be Alphabet\Google\AdWord\KeywordPlanner. The fully qualified class name should also translate into a meaningful file path therefore Alphabet\Google\AdWord\KeywordPlanner would be located in [path_to_source]/Alphabet/Google/AdWord/KeywordPlanner.php
Starting with PHP 5.3.0, a custom autoloader function can be defined to load files based on the path and filename pattern that you define.
# Edit your php to include something like:
spl_autoload_register(function ($class) { include 'classes/' . $class . '.class.php';});
That callback does not implement PSR-4: it does not turn \ into a directory separator. Replace the location (classes/) and filename extension (.class.php) with values that apply to your structure, and map the namespace if you need the PSR-4 layout.
Composer supports PSR-4. If you follow the standard, Composer's vendor autoloader can load your classes.
{
"autoload": {
"psr-4": {
"Alphabet\\": "[path_to_source]"
}
}
}
Regenerate the autoloader file
$ composer dump-autoload
Now in your code you can do the following:
<?php
require __DIR__ . '/vendor/autoload.php';
$KeywordPlanner = new Alphabet\Google\AdWord\KeywordPlanner();