Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To use Composer autoload in implementing PHP namespaces, follow these steps:

  1. 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

  2. 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.

  1. Run composer install in your command line to install your project dependencies.

  2. 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.