Reputation: 2360
I Have a platform writen in PHP, and store a class definition in each file in following way:
filename.php = lower(<class name>) + ".php"
I also use autoload functions to get class name and, using a json generated file (by a custom tool that I made), load the especific file that contains the class definition (I tried to use blob before this, but is too slow).
Why a generated file? Because doing a file search on diretory tree in every request to find the corresponding class is IO intensive.
my generated json class map:
{
"homecontroller": "path/to/dir/homecontroller.php",
"database": "path/to/another/deep/dir/database.php"
}
Today this process of loading json, decoding and store in a array to use in autoload to find classes takes arround 30~50 milliseconds.
autoload, using the generated json class map:
$_runtimefile = "packages/.runtime-map";
$classmap = json_decode(file_get_contents($_runtimefile));;
function __autoload($classname)
{
global $classmap;
$classidentifier = mb_strtolower($classname);
if(!array_key_exists($classidentifier, $classmap)) return;
$filename = __DIR__ . "/" . $classmap->{$classidentifier};
if(!file_exists($filename))
{
debug_print_backtrace();
throw new RuntimeException("File {$filename} not found for class {$classname}");
}
require_once($filename);
}
But I want to do this in a better way, in performance point of view. What are the better ways to load/have a class mapping or autoload for large projects and how I can do this?
Additional informations:
Upvotes: 0
Views: 148
Reputation: 35149
Composer can do it right out of the box - building a list of all classes within one or more sub-directories.
When it comes to actually autoloading them, there are also a number of optional optimisations that can be used to cache the (non-)existence of files so that further checks will not be required. These optimisations would almost always only be useful in production, where deployment is controlled.
Upvotes: 1
Reputation: 2360
Based on suggestions of Elias Soares and Mark Baker I rewrite my code to use file mapping based on a php array.
To create and recreate the php automatically I create d a little C# console program that works fine on my project.
Upvotes: 0