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.
Vendor\Package\Class
. Think of it as the complete address of your class.Project structure:
vendor/
└── jonesrussell/
└── blog/
├── composer.json
└── src/
└── Post/
├── PostController.php
└── PostRepository.php
composer.json
:
{
"name": "jonesrussell/blog",
"autoload": {
"psr-4": {
"JonesRussell\\Blog\\": "src/"
}
}
}
PostController.php
:
'Ready to blog!'];
}
}
Multiple Namespace Roots:
{
"autoload": {
"psr-4": {
"JonesRussell\\Blog\\": "src/",
"JonesRussell\\Blog\\Tests\\": "tests/"
}
}
}
Nested Namespaces: (File location: src/Core/Database/Connection.php
)
config = $config;
}
}
Laravel and Symfony use PSR-4 by default.
Laravel Example:
Symfony Example:
render('blog/index.html.twig');
}
}
composer dump-autoload
.Create test-autoload.php
:
index()); // Should output "Ready to blog!"
Next, we'll cover PSR-6 (caching). This is part of our PSR Standards series.
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