Skip to content

🏗️ AddAutoload

Adds autoload configuration to composer.json, supporting the four types psr-4, psr-0, classmap, and files.

When to use

Use when you need to register a namespace-to-directory mapping, declare a classmap, or declare files for a project. isDev controls whether the entry is written to autoload (production) or autoload-dev (development only, e.g. namespaces for the test suite).

Signature

go
func (c *Composer) AddAutoload(type_ string, namespace string, paths interface{}, isDev bool) error

Parameters

ParameterTypeDescription
type_stringAutoload type: psr-4, psr-0, classmap, files
namespacestringNamespace (e.g. App\); for classmap/files types it can serve as a key placeholder
pathsinterface{}Path(s), can be a string or []string
isDevbooltrue writes to autoload-dev, false writes to autoload

Return value

  • error: Returned when reading or writing fails, or when the existing autoload configuration type does not match (cannot be asserted as map[string]interface{}), returning an invalid autoload configuration error.

Example

go
package main

import (
	"log"

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

func main() {
	comp, err := composer.New(composer.DefaultOptions())
	if err != nil {
		log.Fatal(err)
	}

	// Production PSR-4 autoload
	if err := comp.AddAutoload("psr-4", "App\\", "src/", false); err != nil {
		log.Fatal(err)
	}

	// Development multi-directory PSR-4 autoload
	if err := comp.AddAutoload(
		"psr-4",
		"Tests\\",
		[]string{"tests/", "test-framework/"},
		true,
	); err != nil {
		log.Fatal(err)
	}
}

Advanced

  • 🔄 Internal flow: select autoload/autoload-dev → ensure the sub-map for the type exists → write namespace => pathsWriteComposerJSON.
  • ⚠️ If the existing configuration under the corresponding type is not a map[string]interface{}, an error is returned to avoid breaking the structure.
  • 🚀 After modifying autoload, you must run DumpAutoload to regenerate the optimized mapper for changes to take effect.
  • 📦 To query namespace mappings, use GetNamespaceMap.

Released under the MIT License