Skip to content

🗺️ GetNamespaceMap ​

Extracts the namespace-to-directory mapping from autoload.psr-4 in composer.json.

When to use ​

Use it when you need to know the project's autoloading structure, generate code into the correct directory, or build an IDE index. It reads composer.json directly without running any Composer commands.

Signature ​

go
func (c *Composer) GetNamespaceMap() (map[string]string, error)

Parameters ​

This method takes no parameters.

Return value ​

Return valueTypeDescription
First return valuemap[string]stringNamespace-to-directory mapping, e.g. App\\ → src/
Second return valueerrorReturned when reading or parsing composer.json fails

Note

When a namespace maps to multiple directories, this method takes the first directory as the representative value.

Example ​

go
package main

import (
	"fmt"
	"log"

	"github.com/scagogogo/composer-skills/pkg/composer"
)

func main() {
	comp, err := composer.New(composer.DefaultOptions())
	if err != nil {
		log.Fatalf("initialization failed: %v", err)
	}

	nsMap, err := comp.GetNamespaceMap()
	if err != nil {
		log.Fatalf("failed to get namespace map: %v", err)
	}
	for ns, dir := range nsMap {
		fmt.Printf("%s => %s\n", ns, dir)
	}
}

Advanced ​

  • To read the full composer.json (including the raw autoload and autoload-dev structure), use ReadComposerJson.
  • To regenerate the autoloader, use DumpAutoload.
  • This method only parses psr-4; it does not handle classmap or files rules.

Released under the MIT License