1 | initial version |
To use Composer autoload in implementing PHP namespaces, follow these steps:
Install Composer in your project directory by running the following command in your command line: php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
Create a composer.json
file in your project directory and define your project dependencies including the namespaced classes you will be using. For example:
{
"autoload": {
"psr-4": {
"MyNamespace\\": "src/"
}
},
"require": {
"monolog/monolog": "^2.0"
}
}
In this example, the psr-4
section tells Composer to load any classes in the MyNamespace
namespace from the src/
directory. The require
section specifies that the Monolog logging library should be installed as a dependency.
Run composer install
in your command line to install your project dependencies.
Create a PHP file that uses your namespaced classes. For example:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use MyNamespace\MyClass;
$myObject = new MyClass();
By including the autoload.php
file generated by Composer, your project can now load namespaced classes automatically without having to manually require_once
them.
Note that the namespace declarations in your PHP files must match the namespace specified in your composer.json
file. For instance, if the MyClass
class in the example above has been defined within the MyNamespace
namespace in src/MyClass.php
, it should begin with namespace MyNamespace;
in its PHP code.