php - How to register path in autoload using a single instance.
Sorry about the vague title, but I am trying to find some better alternatives to having to call anAutoloader
class, and theregister
method multiple times, to map class paths as seen below.
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/someclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(_DIR__.'/path/to/anotherclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/anotherclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/anotherclass');
$ClassLoader->register();
$ClassLoader = new Autoloader\Loader(__DIR__.'/path/to/anotherclass');
$ClassLoader->register();
This goes on and on for about 50 lines, and I would like to know how I can handle the autoloading classes with simple few lines solution. I can obviously inject an array, to the constructor:
$ClassLoader = new Autoloader\Loader( ['paths'=>[
'/path/to/class/',
'/path/to/anotherclass',
'/path/to/anotherclass'
]);
$ClassLoader->register();
But, I am not sure if this method is recommended at-least from OOP good practice point of view.
Answer
Solution:
Perhaps this is what you are looking for. For each directory that contains your classes run
::add
.It is effectively the same as with composer though, just less adaptive or performant.
Answer
Solution:
For this you can use Composer: https://getcomposer.org/download/
You will get a file called
composer.phar
. Place this in your project directory, then go to that directory on your command line.Run
php composer.phar init
.This will ask you a few questions which you can ignore, in the end you get a new file called
composer.json
It should look something like this:
Add the
autoload
field, and replacesrc/
with the directory containing your classes. Make sure that directory exists.Then run
php composer.phar install
.This will create a directory called
vendor
. Inside this directory is a file calledautoload.php
.Include this file in the bootstrap of your project, and all classes within your source directory will automatically be loaded in.
Answer
Solution:
Have you looked into spl_autoload_register function?
usage
then place all your classes in "classes" folder and when you initialise them with the
new
keyword, they will be auto-included. Works with static classes also.for example:
or