PHP PSR-4 autoloader
It is great idea to create PSR-4 autoloader packages for PHP. PSR describes a specification for autoloading classes from file paths. It is fully inter-operable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be autoloaded according to the specification.
Thankfully, PSR-0 (now deprecated) and PSR-4 are autoloading standards that actually map your namespaces to real folders. So, if you’re using PSR-0 or PSR-4–which is extremely likely if you’re using Composer or any modern framework– and a compatible autoloader, you can assume that the classes actually are in folders.
Composer and PSR-4 Autoloading
So, let’s say I want the
Devjagat namespace to live in my
Here’s my folder structure for a generic, framework-independent project:
As you can see, the
src folder represents the
Devjagat top level namespace. Since I’m using Composer as my autoloader, all I need to do to get my application to autoload my classes is teach Composer how to map namespaces to folders. Let’s do that using PSR-4.
I’m going to open up
composer.json and add a PSR-4 autoload section:
So you can see: the left side is the namespace that we’re defining (note that you need to escape the slash separators here by doubling them), and the right side is the directory.