https://thewebtier.com/php/psr4-autoloading-php-files-using-composer/
Until now, you should have installed Composer and possibly created a
composer.json file using composer init. If not, you can create one manually now in your project’s root.$ touch composer.json
Setup PSR4 Autoloading
As we’re concerned about setting up PSR4 autoloading here, we’ll edit the
composer.json file to do so."autoload": {
"psr-4": {
"App\\": "app/"
}
}
What’s happening here?
Here the most basic thing to understand is the vendor and application.
Appis vendor name of your application, you can use this name while namespacing files inside of your app directory, such as:namespace App/User;appis your application’s directory, you want to autoload.
Generate Vendor and AutoLoad files
Open up your terminal and type in the following command to install autoloading files in your project.
$ composer dump-autoload -o
This will generate the vendor directory and autoload.php file inside of it.
Use Case
You just need to require once the
autoload.php file once into your index.php file & you’re all set to go.require_once('vendor/autoload.php');
Practical Example
We’ll go through the practical usage of using setting up PSR-4 autoloading in your project, you’ll have to follow along.
Winding up the Basics
- Let’s create a new project and create an
appdirectory inside of it. - Create a
composer.jsonfile and prepare it to autoload files inside your app directory. You should know how to do it now. If not, here it is
"autoload": {
"psr-4": {
"App\\": "app/"
}
},
- Run
composer dump-autoloadto generate the vendor directory and autoload.php
$ composer dump-autoload -o
- Let’s first create a couple of classes inside of app directory
- Create
Settings.phpinsideapp/Config
<?php
namespace App\Config;
class Setings {
//TODO
}
- Create
Utils.phpinsideapp/Helpers
<?php
namespace App\Helpers;
class Utils {
//TODO
}
- Create a new
bootstrap.phpfile inside app directory. This is how I used to do it. You can do it directly inside yourindex.phpfile.
<?php
require __DIR__ .'/../vendor/autoload.php';
- Finally, create an
index.phpfile to test it out.
<?php
require 'app/bootstrap.php';
$config = new App\Config\Settings();
var_dump($config);
You should be able to see the Object class returned in your terminal, like so:
object(App\Config\Settings)#3 (0) {
}
Read more about Namespacing classes in PHP.
No comments:
Post a Comment