Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autoload a single library with Composer

I have installed 3 libraries with Composer for my PHP project. However, I don't need to have autoloading set up for all 3 libraries, for each page load.

Is there a way to only set up auto-loading for a library when I need it? So rather than calling vendor/autoload.php on every page load, I can call vendor/autoload-swiftmailer.php for example?

like image 435
Quasipickle Avatar asked Sep 17 '25 19:09

Quasipickle


1 Answers

It makes no sense to selectively use differently configured autoloaders when using Composer. Here's why:

  1. Composer creates some files that contain the configuration data to do the autoloading. This code is probably the most optimized code even for huge scenarios, and uses different routines if the PHP runtime has more powerful feature (like PHP 5.6 and up). So in the end, probably three or four files have to be read from disk and executed.
  2. PHP uses an Opcache (which you shouldn't disable if you like performance). All files for autoloading are placed in the Opcache. So executing them multiple times is cached, and as fast as possible. When using PHP 5.6 and up, the configuration arrays are defined statically, so it's final form is already cached without any runtime PHP code execution.
  3. If you'd use three exclusive autoloaders, you would likely almost triple the amount of space used in the Opcache. This is valuable memory that cannot be used for something else.
  4. Regardless of the autoloading definitions and the amount of libraries added, the autoloading mechanism will only ever load exactly the files needed to know the code for the classes being used. PHP will not load the WHOLE Swiftmailer classes if you only use the SMTP transport.

Optimizing for performance is a good thing. But you need to have measurements in order to see where time is being used, and you'd need to profile your code in order to get an idea where it is useful to improve performance. A function call that can be reduced from 25 milliseconds to 22 milliseconds is not a worthy goal - unless it is called 100.000 times in a loop.

I'm pretty sure autoloading is not the root of any performance problem - but dealing with three or more different autoload configurations will create a maintenance problem in the long run.

like image 175
Sven Avatar answered Sep 20 '25 10:09

Sven