Home >Backend Development >PHP Tutorial >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.
PSR-4 is your code's automatic file locator. Like a GPS using addresses, PSR-4 uses namespaces to find classes.
VendorPackageClass
. Think of it as the complete address of your class.Project structure:
<code>vendor/ └── jonesrussell/ └── blog/ ├── composer.json └── src/ └── Post/ ├── PostController.php └── PostRepository.php</code>
composer.json
:
<code class="language-json">{ "name": "jonesrussell/blog", "autoload": { "psr-4": { "JonesRussell\Blog\": "src/" } } }</code>
PostController.php
:
<code class="language-php"><?php namespace JonesRussell\Blog\Post; class PostController { public function index() { return ['status' => 'Ready to blog!']; } }</code>
Multiple Namespace Roots:
<code class="language-json">{ "autoload": { "psr-4": { "JonesRussell\Blog\": "src/", "JonesRussell\Blog\Tests\": "tests/" } } }</code>
Nested Namespaces: (File location: src/Core/Database/Connection.php
)
<code class="language-php"><?php namespace JonesRussell\Blog\Core\Database; class Connection { private $config; public function __construct(array $config) { $this->config = $config; } }</code>
Laravel and Symfony use PSR-4 by default.
Laravel Example:
<code class="language-php"><?php namespace App\Http\Controllers; class BlogController extends Controller { public function index() { return view('blog.index'); } }</code>
Symfony Example:
<code class="language-php"><?php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class BlogController extends AbstractController { public function index(): Response { return $this->render('blog/index.html.twig'); } }</code>
composer dump-autoload
.Create test-autoload.php
:
<code class="language-php"><?php require 'vendor/autoload.php'; $controller = new \JonesRussell\Blog\Post\PostController(); var_dump($controller->index()); // Should output "Ready to blog!"</code>
Next, we'll cover PSR-6 (caching). This is part of our PSR Standards series.
The above is the detailed content of PSR-Autoloading Standard in PHP. For more information, please follow other related articles on the PHP Chinese website!