Battle of the Autoloaders: PSR-0 vs. PSR-4
Key Takeaways
- PSR-0 and PSR-4 are autoloading standards in PHP, with PSR-0 defining paths based on a class’s namespace and allowing underscores in class names, while PSR-4 aims to simplify the folder structure and remove remnants of PSR-0.
- PSR-4, referred to as package-oriented autoloading, allows for cleaner packages but is more complicated to implement. It also ensures that autoloaders should never throw exceptions or raise errors, maintaining compatibility with multiple autoloaders.
- Both PSR-0 and PSR-4 have their pros and cons: PSR-4 allows for simpler folder structures but doesn’t show the exact path of a class from its fully qualified name, while PSR-0 can be chaotic but supports developers using older naming conventions and aids in locating a class from its name.
If you’ve gone past the beginner stage in your PHP training, you’ve heard of PSR-0 – an autoloading standard that defines ways to automatically include PHP classes in your code without having to use statements like require and include.
PSR-0
PSR-0 looks at the namespace of a class and discerns its location on the hard drive from that bit of information. For example, the class ZendMailMessage would lead to /path/to/project/lib/vendor/Zend/Mail/Message.php.
PSR-0 also supports underscores in the class names as an alternative, to make transitioning from 5.2 and earlier easier. Zend_Mail_Message would also lead to /path/to/project/lib/vendor/Zend/Mail/Message.php.
Composer
When Composer showed up and took the PHP package management world by storm, things changed. Due to some of its rules, folders often duplicated and became too deep when looking at PSR-0 class installations via Composer. For example, some folder structures ended up like this:
vendor/ vendor_name/ package_name/ src/ Vendor_Name/ Package_Name/ ClassName.php # Vendor_Name\Package_Name\ClassName tests/ Vendor_Name/ Package_Name/ ClassNameTest.php # Vendor_Name\Package_Name\ClassNameTest
This is chaotic at best, because:
The “src” and “tests” directories have to include vendor and package directory names. This is an artifact of PSR-0 compliance.
Therefore, some highly qualified PHP devs got together and put together a suggestion for a new standard: PSR-4.
PSR-4
PSR-4 aims to complement and work together with PSR-0 where necessary, not completely replace it. It can, but doesn’t have to. The main goal of PSR-4 is to remove the remnants of PSR-0 and the pre-5.3 days completely, and allow for a more concise folder structure. With PSR-4, the above folder tree would look like this:
vendor/ vendor_name/ package_name/ src/ ClassName.php # Vendor_Name\Package_Name\ClassName tests/ ClassNameTest.php # Vendor_Name\Package_Name\ClassNameTest
Upgrading PSR-0 was not an option
because PSR-0 does not allow for an intercessory path between any portions of the class name
This is very important – it means that implementing PSR-4, while allowing for much cleaner packages, would be far more complicated to implement. We call PSR-4 package-oriented autoloading, because it favors package cleanliness before simplicity.
The chosen approach
The suggested goals are as follows: keep the PSR-0 rule that all packages must contain at least two namespace levels (vendor and package), make sure the vendor-package combo can map to any folder, and allow for an infix of folders between the vendor-package combo and the rest of the fully qualified class name.
This means we would be able to put our classes anywhere in the package code where it makes sense to us as humans, and still use them smoothly in PHP without writing alternative loading techniques or resorting to manual loading.
Furthermore, the draft explicitly states that a PSR-4 autoloader should never throw exceptions or raise errors simply because multiple autoloaders may be registered, and if one fails to load a class, others should be given the chance to do so – throwing an error and stopping the flow breaks this compatibility. If additional information about the failure is required, one should use a PSR-3 compatible logger or other arbitrary means.
As illustrated in the example file, using the PSR-4 autoloader to load classes from the following structure:
vendor/ vendor_name/ package_name/ src/ Vendor_Name/ Package_Name/ ClassName.php # Vendor_Name\Package_Name\ClassName tests/ Vendor_Name/ Package_Name/ ClassNameTest.php # Vendor_Name\Package_Name\ClassNameTest
would look like this:
vendor/ vendor_name/ package_name/ src/ ClassName.php # Vendor_Name\Package_Name\ClassName tests/ ClassNameTest.php # Vendor_Name\Package_Name\ClassNameTest
where calling new FooBarQuxQuux; would attempt to load from the first registered directory, while new FooBarQuxQuuxTest; would attempt to load from the second.
This example also illustrates the use of multiple folders per single namespace.
Conclusion
There is no silver bullet in autoloading. Each approach brings with itself some pros and cons – PSR-4 would allow for simpler folder structures, but would prevent us from knowing the exact path of a class just by looking at the fully qualified name. PSR-0 on the other hand is chaotic on the hard drive, but supports developers who are stuck in the past (the underscore-in-class-name users) and helps us discern the location of a class just by looking at its name.
How do you feel about PSR-4? Let us know in the comments below, or express your opinion in one of the many debates.
Either way – there’s no doubt package-oriented autoloading is here to stay. If not formally accepted as a standard, then custom implemented by people who need it. It’s up to us to join the discussion and improve the notion enough to reach this formal state.
Frequently Asked Questions about PSR-0 and PSR-4 Autoloading
What is the main difference between PSR-0 and PSR-4?
The primary difference between PSR-0 and PSR-4 lies in the way they handle namespaces and directory structure. PSR-0 requires a direct correlation between namespaces and the directory structure, meaning that each underscore in the namespace corresponds to a directory separator. On the other hand, PSR-4 allows for a more flexible approach, where a portion of the namespace can be mapped to any directory, and the rest of the namespace can be mapped to the subdirectory structure.
Why was PSR-4 introduced when PSR-0 was already in place?
PSR-4 was introduced to overcome some of the limitations of PSR-0. PSR-0’s strict correlation between namespaces and directory structure led to deeply nested directories, which was not always practical or efficient. PSR-4 provides a more flexible approach, allowing developers to map namespaces to any directory, reducing the need for deep directory nesting.
Can I use both PSR-0 and PSR-4 in the same project?
Yes, it is possible to use both PSR-0 and PSR-4 in the same project. However, it’s important to note that they should not be used to autoload the same classes. Using both standards can be beneficial in large projects where some legacy code follows the PSR-0 standard, while newer code follows the PSR-4 standard.
How does PSR-4 improve upon PSR-0?
PSR-4 improves upon PSR-0 by providing a more flexible approach to autoloading. It allows developers to map a portion of the namespace to any directory, reducing the need for deep directory nesting. This makes it easier to manage and navigate the project’s directory structure.
Is PSR-0 deprecated?
Yes, PSR-0 has been marked as deprecated. This means that while it is still functional, it is not recommended for use in new projects. PSR-4 is the recommended standard for autoloading in PHP.
How does autoloading work in PSR-4?
In PSR-4, autoloading works by mapping a portion of the namespace to any directory. The rest of the namespace is then mapped to the subdirectory structure. This allows for a more flexible and efficient approach to autoloading.
What are the benefits of using PSR-4?
PSR-4 offers several benefits, including a more flexible approach to autoloading, reduced need for deep directory nesting, and improved efficiency. It is also the recommended standard for autoloading in PHP, making it a good choice for new projects.
How can I migrate from PSR-0 to PSR-4?
Migrating from PSR-0 to PSR-4 involves changing the way namespaces and directories are mapped. In PSR-4, a portion of the namespace can be mapped to any directory, and the rest of the namespace can be mapped to the subdirectory structure. This may require restructuring your project’s directory structure.
Can I use PSR-4 in older PHP versions?
PSR-4 requires PHP 5.3 or later. If you’re using an older version of PHP, you will need to upgrade in order to use PSR-4.
What is the future of autoloading in PHP?
The future of autoloading in PHP is likely to continue evolving, with new standards and practices being introduced as the language and its ecosystem evolve. However, for the foreseeable future, PSR-4 is the recommended standard for autoloading in PHP.
The above is the detailed content of Battle of the Autoloaders: PSR-0 vs. PSR-4. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
