Es ist möglich, mit einem einfachen Autoloader und es ist nicht so schwer, es zu tun:
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;
}
Aber manchmal muss man die $fileName
anpassen, so funktioniert es mit allen Bibliotheken. Es hängt vom Standard für das automatische Laden ab und davon, wie die Klassennamen der Bibliotheken benannt sind. Manchmal müssen Sie den Klassennamen auf _
aufteilen und das erste Element für den Namen des Directories verwenden und dies auch dem Klassennamen hinzufügen. Ich hatte zum Beispiel eine zweite Bibliothek mit einer Klasse wie Library_Parser
, aber die Struktur war Library/library-parser.php
.
Die erste Bibliothek arbeitete direkt mit dem obigen Code und alle Klassen wurden automatisch geladen.
Der Code wurde von http://www.sitepoint.com/autoloading-and-the-psr-0-standard/ übernommen, aber ich musste einige Code-Teile (zusätzliche Unterstriche und Backslashes) korrigieren. Ich habe die Standardlösung PSR-0 verwendet.
PSR-4-Version von 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();
Die akzeptierte Antwort ist PSR-0-konform, für eine PSR-4-Lösung finden Sie http://stackoverflow.com/questions/39571391/psr4-auto- load-without-composer –