My models are inside the namespace App\Model. With composer auto-loading, they are only loaded when in use. But I want every class/interfaces/traits inside the App\Model to be preloaded to this script file (SchemaGenerator.php which is under App namespace) without the use of Model instances inside the class)
Similar Example:
src/Test.php:
<?php
namespace App;
class Test{
public static function run(){
print_r(get_declared_classes());
}
}
Test::run();
?>
Medicine.php:
<?php
namespace App\Model;
class Medicine{
// --snip--
}
composer.json:
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
PHP class autoloading in general and Composer implementation in particular work by crafting a file path following a set of rules (programmed in PHP code) and attempting to include such file. The whole process is triggered when PHP executes a piece of code that requires a class definition for a not yet defined class. Here's a quick and dirty implementation to illustrate that:
The only difference with what Composer does is that this tool implements well-known naming conventions (PSR-0 and PSR-4) to map names with files.
What you need is essentially the other way round: rather than getting a file from a class name, you need a class name from a file. There isn't a builtin functionality, neither in PHP nor in Composer, but it should be easy to do:
Use file system functions to traverse the
srcsubdirectory where you expect your entity classes to be.Include the files you find. This is safe, as long are you're careful with your conventions and your files only contain class definitions.
Get the list of declared classes and filter by namespace.
For reference, this is how the Doctrine ORM library finds migration classes.