Real purpose of autoloading in PHP

I thought using an autoloader is to help me get rid of a long list of "include"s, but then there are long namespaces instead and I have to write a long list of "use"s at the top of each of my scripts so…,
then what is really the purpose of an autoloader in the first place?
Are namespaces more readable than real paths? or there are some other reasons?

You can make a directory structure within your include directory that mimics the structure of the namespaces, that way the autoloader finds them by following the path of the namespace.

1 Like

You don’t need to use use, you can just use the full class name throughout your script. Which is better will depend on preference, how many times you’re using the class and how long the namespace is.

In theory namespaces are more flexible than includes because with include '../classes/library/foo.php if the file is not in that location your code won’t work. Whereas use Library\Foo, the class could be located anywhere and the autoloader will find it. In practice, most autoloaders couple to the namespace to the filesystem anyway

If you find yourself with a “long list”, you may want to rethink your approach. If you find yourself writing a class that depends on more than 3-4 other classes it’s likely your class is doing too much and should be broken up. Take a look at the single responsibility principle.

Further reading:
http://misko.hevery.com/code-reviewers-guide/flaw-class-does-too-much/

http://nikic.github.io/2011/12/27/Dont-be-STUPID-GRASP-SOLID.html

3 Likes

After about 2 years of fooling around with autoloaders and namespaces, I found this link https://phpenthusiast.com/blog/how-to-autoload-with-composer and it helped me out a lot. It also caused me to hit myself for the solution was so obvious. :grin:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.