Global autoload

Hello roots community,

As you know, there is a global autoloading with bedrock and in most of the cases it works just perfectly. Nevertheless sometimes it does not work.

In my case, my bedrock site uses a homemade plugin as a dependency and this plugin also has a dependency that is loaded to early and generates an error. The error is exactly the same as described in this GitHub issue (not reported on roots).

I get something like that in my composer.json (dependency of the plugin level):

 "autoload": {
 "files": [
     "./includes/my-field/field.php"
 ],
 "psr-4": {
     "Carbon_Field_YOURFIELDNAME\\": "./includes/my-field/core/"
 }

}

My bedrock project automatically generated the autoload files, including the loading of the dependency of my plugin when I required my plugin through composer.

As a temporary solution, I removed the autoloading of this specific dependency from autoload_static.php, autoload_real.php, etc at the bedrock root level. And I manually required autoload.php of the dependency in the plugin initalisation procedure. Well, it works on my dev env, but this is clearly not suitable for production.

I don’t want that the dependency of my plugin to be loaded globally like that, I prefer to handle it manually in my plugin. How should I proceed?

I noticed that there is a similar topic, however I did not help me.

My guess is that your problem is a result of using the files autoload mechanism. Unlike PSR-4 autoloading, which loads things as needed anything in the files array is loaded for every single request. This probably means your file is loaded at some point by a request that is made “before” things it needs have been loaded. The best solution would probably be to set up your homemade plugin to be loaded w/ PSR-4, and the instantiate it as-needed in your theme, an mu-plugin, etc. That way it won’t be loaded on requests where it isn’t needed.

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.