PSR-4 works by translating a class's fully qualified namespace into a file path. The autoloader takes the namespace prefix, replaces namespace separators with directory separators, appends the class name with .php, and includes that file. This happens at runtime when a class is first used, triggering the autoloader to find and load the file automatically.
Why designed this way?
PSR-4 was designed to replace older, inconsistent autoloading methods by providing a clear, standardized way to map namespaces to directories. This reduces errors, improves interoperability between libraries, and supports modern PHP development practices. Alternatives like PSR-0 were more complex and less efficient, so PSR-4 simplified the rules for better performance and clarity.
āāāāāāāāāāāāāāāāā
ā Class Used in ā
ā Code ā
āāāāāāāā¬āāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāā
ā Autoloader ā
ā (PSR-4 logic) ā
āāāāāāāā¬āāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Map namespace prefix to base ā
ā directory ā
āāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Convert namespace parts to ā
ā folder path + class.php ā
āāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāā
ā
ā¼
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Include the file if exists ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā