Ask Your Question
4

How to use Composer autoload in implementing PHP namespaces?

asked 2021-11-12 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-08-24 14:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-12 11:00:00 +0000

Seen: 24 times

Last updated: Aug 24 '22