Skip to content

Instantly share code, notes, and snippets.

@mrclay
Last active February 2, 2016 19:27
Show Gist options
  • Save mrclay/1935230 to your computer and use it in GitHub Desktop.
Save mrclay/1935230 to your computer and use it in GitHub Desktop.
Crude, but tiny single-library PHP autoloading setups
<?php
// In the snippets below, you must replace '/path/to/lib' with the correct path.
// does not support namespaces with underscores
spl_autoload_register(function ($class) {
$file = __DIR__ . '/path/to/lib/' . strtr(ltrim($class, '\\'), '_\\', '//') . '.php';
is_readable($file) && (require $file);
});
// for a particular namespace
spl_autoload_register(function ($class) {
$class = ltrim($class, '\\');
if (0 !== strpos($class, 'NamespaceName\\')) {
return;
}
$file = dirname(__DIR__) . '/path/to/lib/' . strtr($class, '_\\', '//') . '.php';
is_readable($file) && (require $file);
});
// full PSR-0 compliant
spl_autoload_register(function ($class) {
$classPaths = array(
// class paths here...
);
$pieces = explode('\\', ltrim($class, '\\'));
$pieces[count($pieces) - 1] = strtr($pieces[count($pieces) - 1], '_', '/');
$relativePath = '/' . implode('/', $pieces) . '.php';
foreach ($classPaths as $classPath) {
if (is_readable($classPath . $relativePath)) {
require $classPath . $relativePath;
return;
}
}
});
// PSR-0 plus Zend Framework 1 support
set_include_path(get_include_path() . PATH_SEPARATOR . '/path/to/zf1/library');
spl_autoload_register(function ($class) {
if (0 === strpos($class, 'Zend_')) {
// We have to use require_once with a relative path, like ZF1 does. If not, PHP will
// try to load the file twice.
$relativePath = str_replace('_', '/', $class) . '.php';
if (function_exists('stream_resolve_include_path')) {
$resolvedPath = stream_resolve_include_path($relativePath);
if ($resolvedPath && is_readable($resolvedPath)) {
require_once $relativePath;
return;
}
} else {
// No way to check if path will resolve, let's just hope.
require_once $relativePath;
return;
}
}
$classPaths = array(
// class paths here...
);
$pieces = explode('\\', ltrim($class, '\\'));
$pieces[count($pieces) - 1] = strtr($pieces[count($pieces) - 1], '_', '/');
$relativePath = '/' . implode('/', $pieces) . '.php';
foreach ($classPaths as $classPath) {
if (is_readable($classPath . $relativePath)) {
require $classPath . $relativePath;
return;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment