I'm currently working on a Laravel project that needs to access classes from its parent directory.
composer.json > PSR-4:
"psr-4": {
...
"ModuleA\\": "../ModuleA/baseObjects",
"ModuleB\\": "../ModuleB/baseObjects"
}
Example file structure:
/var/www
+- /xxx (project)
+- /ModuleA
+- /baseObjects
- configClass.inc
+- /ModuleB
+- /baseObjects
- configClass.inc
+- /laravel
- composer.json
I run composer dump-autoload
but the project still can't find ModuleA\configClass
neither ModuleB\configClass
.
Furthermore, inside my autoload_psr4.php
, the above gets referenced as following:
'MobuleA\\' => array($baseDir . '/../MobuleA/baseObjects')
'MobuleB\\' => array($baseDir . '/../MobuleB/baseObjects')
The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.
Classmap vs. php , when composer reads that we are using autoload classmap , it is scanning all the files in the mentioned directories (in composer. json file) and create an array of namespaces and the corresponding paths. Note: adding new files requires composer dumpautoload to regenerate the mapping.
Timo Reymann. Compatible with IntelliJ IDEA Ultimate, PhpStorm. Tutorials. This is a simple plugin to trigger composer to create a new autoload file when you move, create or delete PHP files in your project.
Basically, when you use a class in your application, the autoloader checks if it's already loaded, and if not, the autoloader loads the necessary class into memory. So the class is loaded on the fly where it's needed—this is called autoloading.
PSR-4 requires the loaded files to have a namespaced class, and the namespace structure has to match the directory structure, relative to the "base directory" defined in the configuration (http://www.php-fig.org/psr/psr-4/).
So, in file /var/xxx/ModuleA/baseObjects/configClass.inc
should be the class
namespace ModuleA\baseObjects;
class configClass {
...
}
Then in var/www/laravel/composer.json
you could have
"psr-4": {
"App\\": "app/",
"ModuleA\\": "../ModuleA"
}
Which means: "directory ../ModuleA
should be the root for ModuleA
namespace, then follow subnamespaces by matching subdirectories from there".
Use classmap autoload will solve this problem.
{
...
"autoload": {
"classmap": ["ModuleA/", "ModuleB/"]
}
}
It could be used with PSR-4
{
...
"autoload": {
"psr-4": {
"Acme\\": "src/Acme/"
},
"classmap": ["ModuleA/", "ModuleB/"]
}
}
Ref: https://getcomposer.org/doc/04-schema.md#classmap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With