Skip to content

Instantly share code, notes, and snippets.

@kumaxim
Created February 6, 2016 10:00
Show Gist options
  • Select an option

  • Save kumaxim/054a11283cd08f2550b2 to your computer and use it in GitHub Desktop.

Select an option

Save kumaxim/054a11283cd08f2550b2 to your computer and use it in GitHub Desktop.
Autoloader PSR-4 is correspond PSR-2 class name
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'RMLcustomizer\\';
// base directory for the namespace prefix
$baseDir = __DIR__ . DIRECTORY_SEPARATOR;
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relativeClass = substr($class, $len);
// build specific path
// First letter is no matter
$relativeFile = $relativeClass[0];
for ($position = 1; $position < strlen($relativeClass); $position++) {
// Latter has upper case
if (ctype_upper($relativeClass[$position])) {
// and is not namespace divider
if (false === in_array($relativeClass[$position - 1], array('\\', '/'))) {
$relativeFile .= '-' . $relativeClass[$position];
continue;
}
}
$relativeFile .= $relativeClass[$position];
}
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = strtolower($baseDir . str_replace('\\', '/', $relativeFile) . '.php');
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
@kumaxim
Copy link
Copy Markdown
Author

kumaxim commented Feb 6, 2016

For example, I have file path ./hook/post-details.php. It file consist class postDetails. Default psr-4 example isn't work. My code is work for this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment