使用简单的自动加载器就可以做到这一点,而且并不难做到:
function __autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
// $fileName .= $className . '.php'; //sometimes you need a custom structure
//require_once "library/class.php"; //or include a class manually
require $fileName;
}
但有时你必须调整$fileName
所以它适用于所有库。这取决于自动加载的标准以及库的类名的命名方式。有时你必须将类名分开_
并使用第一个元素作为目录名称,并将其也添加到类名称中。例如,我有第二个图书馆,其中有一个类Library_Parser
但结构是Library/library-parser.php
.
第一个库直接使用上面的代码,并且所有类都会自动加载。
代码取自http://www.sitepoint.com/autoloading-and-the-psr-0-standard/ http://www.sitepoint.com/autoloading-and-the-psr-0-standard/但我必须纠正一些代码部分(额外的下划线和反斜杠)。我使用了 PSR-0 标准溶液。
PSR-4版本由https://stackoverflow.com/users/1740659/thibault https://stackoverflow.com/users/1740659/thibault:
function loadPackage($dir)
{
$composer = json_decode(file_get_contents("$dir/composer.json"), 1);
$namespaces = $composer['autoload']['psr-4'];
// Foreach namespace specified in the composer, load the given classes
foreach ($namespaces as $namespace => $classpaths) {
if (!is_array($classpaths)) {
$classpaths = array($classpaths);
}
spl_autoload_register(function ($classname) use ($namespace, $classpaths, $dir) {
// Check if the namespace matches the class we are looking for
if (preg_match("#^".preg_quote($namespace)."#", $classname)) {
// Remove the namespace from the file path since it's psr4
$classname = str_replace($namespace, "", $classname);
$filename = preg_replace("#\\\\#", "/", $classname).".php";
foreach ($classpaths as $classpath) {
$fullpath = $dir."/".$classpath."/$filename";
if (file_exists($fullpath)) {
include_once $fullpath;
}
}
}
});
}
}
loadPackage(__DIR__."/vendor/project");
new CompanyName\PackageName\Test();