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

Undress AI Tool
Undress images for free

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

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

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

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
