简体   繁体   中英

When I auto-load a class/file with composer, what is actually happening behind the scenes?

I haven't been able to find a strait answer to this question yet elsewhere online and was wondering how exactly composer autoloading worked.

When I autoload a class using PSR-0 or classmap what is actually happening behind the scenes? Is it just calling include(or some include variant) on the the specified file in the specified path. Is it actually skimming the file for class definitions and constructing its own file to include? Is it doing something that isn't analogous to a file include?

Thanks in advance!

A PSR-0 autoloader is simply a function attached to the global PHP process with spl_autoload_register() . That registered function is called whenever PHP needs to instantiate a class that isn't yet known, so this is the last moment to make the classes code known before PHP fails.

And the implementation of that autoloading can be either pretty sophisticated, or pretty simple, but in every case it will use either include() or require() (possibly with _once , but this is not really needed) to make the class code known to PHP. You could also implement a call to eval() to dynamically add some code that declares the class needed, but this would just be for academic used - I haven't seen it being used in real cases.

The same applies to the classmap loading. The classmap array contains names of classes as keys, and the filename of the containing file as value. This is for cases where there is no PSR-0-compatible ruleset mapping between class name and file path.

If you want more details of how Composer does the autoloading, you should have a look at the generated files inside vendor/composer . Basic knowledge about how PHP autoloading works in general would help understand what happens there.

Behind the scenes composer use spl_autoload_register to register an autoloader function which include your class.

The registered function follows a standardized namespace/path resolution algorithm (basically consider all "\\" or "_" in your class name as path separators from a specified base directory) to find the php file to include.

Also, when you run composer install it create a cached index of relation between paths and namespace to speed up the path resolution.

You can dig in the Github repository and see it for yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM