php - How to dynamically load a list of classes?

920

I would like to load a list of classes dynamically. The general idea would be to have a sort of manifest/config file that contains an array list of classes and then they would "automatically" be loaded into my application instead of needing to manually do something like

use App\Controllers\UserController;
use App\Controllers\ContractController;
use App\Controllers\SubscriptionController;
etc...

It seems there must be some way to achieve this as the Laravel framework does something similar with service providers. You register the classes once inconfig/app.php and then these provider classes are auto loaded onto the app.

265

Answer

Solution:

If you are looking for a native/homemade solution without any PSR0/4 convention or composer package manager, you can consider use spl_autoload_register and __autoload to make your own logic to resolve the classes.

But i would strongly recommend composer and PSR4 standarts for this.

Here is the example of a customer resolver/loader class https://www.php.net/manual/en/function.spl-autoload-register.php#102180

People are also looking for solutions to the problem: php - Migration & seed files to sql script

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.