huge icon indicating copy to clipboard operation
huge copied to clipboard

[question] Autoloading controllers (composer)

Open elbenjaz opened this issue 8 years ago • 1 comments

Hi,

If we change in composer.json: (adding application/controller/) from:

L15: "psr-4": { "": ["application/core/", "application/model/"] }

to:

L15: "psr-4": { "": ["application/controller/", "application/core/", "application/model/"] }

it's possible to delete the "require()" statements in core/Application.php

L37: require Config::get('PATH_CONTROLLER') . $this->controller_name . '.php';
L51: require Config::get('PATH_CONTROLLER') . 'ErrorController.php';
L57: require Config::get('PATH_CONTROLLER') . 'ErrorController.php';

¿What do you think? ¿Is it a good idea? ¿Is there an another reason for those "require()"?

Have a nice weekend!

elbenjaz avatar Feb 19 '16 20:02 elbenjaz

I think you can do this. It's working quite good. Additionally you need to change line 33 in Application.php and check if class exist instead of file exist:

if (class_exists($this->controller_name)) {

Is it a good idea? I don't know. I can see some pros and cons. You can use controller in other controller without any additional actions, no more require files etc.

But this approach can have an impact on the application performance. AFAIK Composer autoloader search for a classes by performing calls to the file_exists function. So if your app contains a lot classes (vendor packages, controllers, models, core classes) the autoloader must go through all of them and fire up file_exists function. Optimize autoloader can fix that issue. Just run php composer.phar dumpautoload -o This creates a "classmap" mapping each class to its file.

Note if you add, move, edit, delete, reneme any class or run php composer.phar update you have to run Composers optimizer again.

Update: BTW Composer optimize should be run before go for production all the time https://getcomposer.org/doc/03-cli.md#dump-autoload

slaveek avatar Feb 20 '16 13:02 slaveek