Why I love PHP now, after 20 years of struggle: PSR-4 Autoloader

Brian Ruff
2 min readJan 15, 2022
“Hella easier to use classes now”

PHP is finally easy now thanks to the PSR-4 Autoloader. The experience of using it has been the most empowering step in my 20 years professional relationship with the PHP programming language. It has been has been awesome. It’s finally pushed me over the edge into expert level control. It’s been a huge time saver. It’s taken me from average (see mediocre) ability to feeling like a master app builder. I could go on, but you should try this awesome feature for yourself if you are using PHP.

It’s extremely easy to set up via Composer. Also see: PSR-R autoloading examples in the Composer docs.

{
"autoload": {
"psr-4": {"App\\": "src/"}
}
}

Finally, real structure in native PHP:

The main thing I like about using PSR-4 Autoloading is that it’s given my projects structure in a way no 3rd-party framework ever has.

The way I like to structure my apps is by feature instead of archetype. I learned about this concept in from the PHP Expert Nikola Poša’s “On Structuring PHP Projects” blog post.

Examples from Nikola’s post:

Feature based directory structure (easier):

src/
Cart/
Product/
User/

Archetype based structure:

src/
Controller/
Repository/
Service/

How it helps me organize APIs:

Along with features getting their own folder, I also like to create a new folder for each API, as well as a framework folder for the utility classes that all my apps use:

src/
Framework/
User/
Checkout/
Wishlist/
AmazonWebServices/
Dropbox/
Vimeo/
Google/
Youtube/
Analytics/
etc.

This structure makes it easy to call classes on the fly:

require './autoloader.php'; // start composer// call up the class when you need it: 
$speedTest = new GenericApp\Framework\SpeedTest();
$speedTest->startSpeedTest();
// page code here$speedTest->endSpeedTest();

It may not look like much in the context of a speed test, but once you apply this same simple method to a big complex app it makes thousands of classes and functions at your disposal in a clean and organized way. No need for extra layers of abstraction and 3rd party frameworks. Just simple, clean, fast, PHP.

I’m happy to have learned about this technique and hope that you will give it a shot if you haven’t already. Positive and negative feedback welcomed in the comments.

--

--

Brian Ruff
0 Followers

Brian Ruff. Founder of Locomojo.com a free storefront where artists and creatives get 100% profits. Writing about my journey here.