[wp-trac] [WordPress Trac] #21300: Implement autoloader compatible with PSR-0 / PSR-4 for plugins and themes
WordPress Trac
noreply at wordpress.org
Fri Feb 14 10:48:01 UTC 2014
#21300: Implement autoloader compatible with PSR-0 / PSR-4 for plugins and themes
-----------------------------+-------------------------
Reporter: dave1010 | Owner:
Type: feature request | Status: closed
Priority: normal | Milestone:
Component: Bootstrap/Load | Version:
Severity: normal | Resolution: maybelater
Keywords: | Focuses:
-----------------------------+-------------------------
Comment (by Denis-de-Bernardy):
Fwiw, here's a simple autoloader that I'd love to see added to WP, so as
to not need to constantly add the same lines of code in each plugin.
Not that the lines are very long:
{{{
# PSR-4 Autoloader
spl_autoload_register(function($class) {
if ($class !== strstr($class, __NAMESPACE__ . '\\')) return;
$file = substr($class, strlen(__NAMESPACE__));
$file = str_replace('\\', DIRECTORY_SEPARATOR, $file) . '.php';
$file = __DIR__ . DIRECTORY_SEPARATOR . 'src' . $file;
if (file_exists($file)) {
require $file;
}
}, true);
}}}
Still, I'd not need to constantly remember to copy/paste them if WP
version offered something similar, e.g.:
{{{
class WP_Autoloader
function __construct($namespace, $path) {
$this->namespace = $namespace;
$this->path = $path;
}
function load($class) {
if ($class !== strstr($class, $this->namespace . '\\')) return;
$file = substr($class, strlen($this->namespace));
$file = str_replace('\\', DIRECTORY_SEPARATOR, $file) . '.php';
$file = $this->path . $file;
if (file_exists($file)) {
require $file;
}
}
}
wp_register_autoloader($namespace, $path) {
$loader = new WP_Autoloader($namespace, $path);
spl_autoload_register(array($loader, 'load'), true);
}
}}}
Or perhaps a variation of the above that accommodates prefixes instead of
namespaces indifferently (I'll happily supply the patch if it's +1'ed). At
any rate, I like this idea and think we should re-open the ticket.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/21300#comment:18>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list