"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Detailed explanation of PSR automatic loading standards in PHP

Detailed explanation of PSR automatic loading standards in PHP

Posted on 2025-04-29
Browse:271

PSR-Autoloading Standard in PHP

Ahnii!

Remember PHP's manual require days? Last week, I helped a team upgrade their legacy app – over 50 require statements per file! Let's see how PSR-4 autoloading solves this.

Understanding PSR-4 (5 minutes)

PSR-4 is your code's automatic file locator. Like a GPS using addresses, PSR-4 uses namespaces to find classes.

Key Concepts (2 minutes)

  1. Fully Qualified Class Name (FQCN): Vendor\Package\Class. Think of it as the complete address of your class.
  2. Directory Structure: A well-organized project directory with namespace-to-directory mappings.

Real-World Example (10 minutes)

Project structure:

vendor/
└── jonesrussell/
    └── blog/
        ├── composer.json
        └── src/
            └── Post/
                ├── PostController.php
                └── PostRepository.php

Setting Up Composer (3 minutes)

composer.json:

{
    "name": "jonesrussell/blog",
    "autoload": {
        "psr-4": {
            "JonesRussell\\Blog\\": "src/"
        }
    }
}

Creating Classes (2 minutes)

PostController.php:

 'Ready to blog!'];
    }
}

Common Patterns (5 minutes)

Multiple Namespace Roots:

{
    "autoload": {
        "psr-4": {
            "JonesRussell\\Blog\\": "src/",
            "JonesRussell\\Blog\\Tests\\": "tests/"
        }
    }
}

Nested Namespaces: (File location: src/Core/Database/Connection.php)

config = $config;
    }
}

Framework Examples (5 minutes)

Laravel and Symfony use PSR-4 by default.

Laravel Example:

Symfony Example:

render('blog/index.html.twig');
    }
}

Troubleshooting (3 minutes)

  • "Class Not Found" Errors: Run composer dump-autoload.
  • Directory Structure Issues: Ensure your directory structure matches your namespaces (case-sensitive!).

Testing (2 minutes)

Create test-autoload.php:

index()); // Should output "Ready to blog!"

Next Steps

Next, we'll cover PSR-6 (caching). This is part of our PSR Standards series.

Resources

  • Official PSR-4 Specification
  • Composer Autoloading Documentation
  • Series Example Repository (v0.3.0 - PSR-4 Implementation)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3