亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Key Takeaways
PSR-4
Composer
The chosen approach
Conclusion
Frequently Asked Questions about PSR-0 and PSR-4 Autoloading
What is the main difference between PSR-0 and PSR-4?
Why was PSR-4 introduced when PSR-0 was already in place?
Can I use both PSR-0 and PSR-4 in the same project?
How does PSR-4 improve upon PSR-0?
Is PSR-0 deprecated?
How does autoloading work in PSR-4?
What are the benefits of using PSR-4?
How can I migrate from PSR-0 to PSR-4?
Can I use PSR-4 in older PHP versions?
What is the future of autoloading in PHP?
Home Backend Development PHP Tutorial Battle of the Autoloaders: PSR-0 vs. PSR-4

Battle of the Autoloaders: PSR-0 vs. PSR-4

Feb 23, 2025 am 08:45 AM

Battle of the Autoloaders: PSR-0 vs. PSR-4

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

See all articles