⚙️ Configuration
The Composer SDK's configuration module covers all capabilities of the composer config subcommand — validation, cache, config item read/write, source tracking, platform requirement checking, and structured config --list parsing. All methods are attached to the core type Composer, defined in pkg/composer/config.go.
Difference from composer.json File Operations
Methods on this page go through the composer config subcommand (which actually calls the composer binary and affects global/project configuration). If you just want pure file read/write of the config field or top-level properties in composer.json, see composer.json Operations (ReadComposerJSON, SetConfig, SetProperty, AddRequire, etc.).
Package path: github.com/scagogogo/composer-skills/pkg/composer
Capability Overview ⚙️
| Method | Purpose | Return Value |
|---|---|---|
Validate | Validate composer.json | error |
GetComposerHome | Get Composer home directory | (string, error) |
ClearCache | Clear Composer cache | error |
GetConfigWithGlobal | Read config item, optional global | (string, error) |
SetConfigWithGlobal | Set config item, optional global | error |
ListConfig | List all config values | (string, error) |
ListConfigWithGlobal | List global or project config | (string, error) |
GetConfigSource | Query source file of config item | (string, error) |
CheckPlatformReqs | Check platform requirements | (string, error) |
ValidateComposerJson | Validate composer.json with options | error |
GetConfigStructured | List config and return as structured result | (*ConfigResult, error) |
⚙️ Validate
Validate composer.json, equivalent to composer validate.
When to Use
Use after writing or modifying composer.json, before committing code, to confirm the file structure and fields are valid.
Signature
func (c *Composer) Validate() errorReturn Values
error: Error returned on validation failure.
Example
package main
import (
"log"
"github.com/scagogogo/composer-skills/pkg/composer"
)
func main() {
comp, err := composer.New(composer.DefaultOptions())
if err != nil {
log.Fatalf("Failed to initialize Composer: %v", err)
}
if err := comp.Validate(); err != nil {
log.Fatalf("composer.json invalid: %v", err)
}
fmt.Println("composer.json validation passed")
}Advanced
For finer-grained validation, use ValidateComposerJson(strict, withDependencies), or refer to ValidateStrict, ValidateSchema, ValidateQuiet and other variants in the Validate module.
⚙️ GetComposerHome
Get Composer home directory, equivalent to composer config --global home.
When to Use
Use to locate Composer's global configuration file, global vendor directory, or auth.json.
Signature
func (c *Composer) GetComposerHome() (string, error)Return Values
string: Composer home directory path (whitespace trimmed).error: Error returned on failure.
Example
home, err := comp.GetComposerHome()
if err != nil {
log.Fatalf("Failed to get Composer home directory: %v", err)
}
fmt.Printf("Composer home directory: %s\n", home)Convenience Alias
GetComposerHomeDir in the Convenience module provides the same capability, plus GetCacheDir, GetVendorDir, GetBinDir and other directory location methods.
⚙️ ClearCache
Clear Composer cache, equivalent to composer clear-cache.
When to Use
Use when package downloads are corrupted, mirror sync is lagging, or disk space is tight.
Signature
func (c *Composer) ClearCache() errorReturn Values
error: Error that occurred during clearing.
Example
if err := comp.ClearCache(); err != nil {
log.Fatalf("Failed to clear cache: %v", err)
}
fmt.Println("Cache cleared")⚙️ GetConfigWithGlobal
Get the value of a Composer config item, optionally reading global config, equivalent to composer config [--global] setting.
When to Use
Use when you need to read a config item (like process-timeout, preferred-install, bin-dir) in your program.
Signature
func (c *Composer) GetConfigWithGlobal(setting string, global bool) (string, error)Parameters
| Parameter | Type | Description |
|---|---|---|
setting | string | Config item name, e.g., process-timeout |
global | bool | true reads global config, false reads project config |
Return Values
string: Config item value (whitespace trimmed).error: Error returned on failure.
Example
// Read project-level process-timeout
timeout, err := comp.GetConfigWithGlobal("process-timeout", false)
if err != nil {
log.Fatalf("Failed to read config: %v", err)
}
fmt.Printf("process-timeout = %s\n", timeout)
// Read global bin-dir
binDir, err := comp.GetConfigWithGlobal("bin-dir", true)
if err != nil {
log.Fatalf("Failed to read global config: %v", err)
}
fmt.Printf("global bin-dir = %s\n", binDir)⚙️ SetConfigWithGlobal
Set the value of a Composer config item, optionally writing to global config, equivalent to composer config [--global] setting value.
When to Use
Use when you need to programmatically adjust a config item — for example, switching preferred-install to dist in CI, or setting global bin-dir when initializing a container.
Signature
func (c *Composer) SetConfigWithGlobal(setting string, value string, global bool) errorParameters
| Parameter | Type | Description |
|---|---|---|
setting | string | Config item name |
value | string | Value to set |
global | bool | true writes to global config, false writes to project config |
Return Values
error: Error returned on failure.
Example
// Set preferred-install to dist globally
if err := comp.SetConfigWithGlobal("preferred-install", "dist", true); err != nil {
log.Fatalf("Failed to set global config: %v", err)
}
// Set process-timeout at project level
if err := comp.SetConfigWithGlobal("process-timeout", "300", false); err != nil {
log.Fatalf("Failed to set project config: %v", err)
}Write Location
When global=false, the value is written to the config field of the current project's composer.json; when global=true, it's written to the global config.json. Ensure the Composer's working directory is correct.
⚙️ ListConfig
List all config values, equivalent to composer config --list.
When to Use
Use when you need to see all Composer config items and their values for the current project at once, commonly for debugging and diagnostics.
Signature
func (c *Composer) ListConfig() (string, error)Return Values
string: List of all config values (raw output).error: Error returned when listing config fails (wrapped as "failed to list config").
Example
output, err := comp.ListConfig()
if err != nil {
log.Fatalf("Failed to list config: %v", err)
}
fmt.Println("Config list:")
fmt.Println(output)Advanced
For structured results (split by Key/Value/Source), use GetConfigStructured; to distinguish global/project, use ListConfigWithGlobal.
⚙️ ListConfigWithGlobal
List all config values, optionally listing global or project config, equivalent to composer config --list [--global].
When to Use
Use when you need to view global and project-level config separately — for example, to troubleshoot which layer overrides a config item.
Signature
func (c *Composer) ListConfigWithGlobal(global bool) (string, error)Parameters
| Parameter | Type | Description |
|---|---|---|
global | bool | true lists global config, false lists project config |
Return Values
string: Config value list.error: Error returned when listing config fails.
Example
// List global config
globalCfg, err := comp.ListConfigWithGlobal(true)
if err != nil {
log.Fatalf("Failed to list global config: %v", err)
}
fmt.Println("Global config:")
fmt.Println(globalCfg)
// List project config
projectCfg, err := comp.ListConfigWithGlobal(false)
if err != nil {
log.Fatalf("Failed to list project config: %v", err)
}
fmt.Println("Project config:")
fmt.Println(projectCfg)⚙️ GetConfigSource
Get source information for a specified config item, equivalent to composer config key --source.
When to Use
Use to debug config issues — it tells you whether a value was loaded from the project composer.json, global config.json, or a default.
Signature
func (c *Composer) GetConfigSource(key string) (string, error)Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Config item name to query source for |
Return Values
string: Source information for the config item (whitespace trimmed).error: Error returned on failure (wrapped as "failed to get config source").
Example
source, err := comp.GetConfigSource("preferred-install")
if err != nil {
log.Fatalf("Failed to get config source: %v", err)
}
fmt.Printf("Source of preferred-install: %s\n", source)⚙️ CheckPlatformReqs
Check platform requirements, equivalent to composer check-platform-reqs.
When to Use
Use before deployment to confirm the current PHP version and extensions meet the platform requirements of the project (including dependencies).
Signature
func (c *Composer) CheckPlatformReqs() (string, error)Return Values
string: Raw output of platform requirement check.error: Error returned on check failure.
Example
output, err := comp.CheckPlatformReqs()
if err != nil {
log.Fatalf("Platform requirements check failed: %v", err)
}
fmt.Println(output)Advanced
For structured results (each requirement's Package/Version/Status/Required), use CheckPlatformReqsStructured (defined in result_types.go, returns *PlatformCheckResult); for formatted output, see CheckPlatformReqsWithFormat (additional_methods.go).
⚙️ ValidateComposerJson
Validate composer.json with options, equivalent to composer validate [--strict] [--with-dependencies].
When to Use
Use when you need strict mode validation, or want to check dependencies' composer.json validity along with the project.
Signature
func (c *Composer) ValidateComposerJson(strict bool, withDependencies bool) errorParameters
| Parameter | Type | Description |
|---|---|---|
strict | bool | true enables --strict strict mode |
withDependencies | bool | true checks dependencies' composer.json as well |
Return Values
error: Error returned on validation failure.
Example
// Strict mode + check dependencies
if err := comp.ValidateComposerJson(true, true); err != nil {
log.Fatalf("Validation failed: %v", err)
}
fmt.Println("composer.json and its dependencies all passed validation")⚙️ GetConfigStructured
List config and return as structured result. Internally executes composer config --list and parses with ParseConfigList.
When to Use
Use when you need to iterate config items and process by Key/Value/Source in your program — for example, generating config reports or comparing differences between two environments.
Signature
func (c *Composer) GetConfigStructured() (*ConfigResult, error)Return Values
*ConfigResult: Structured config result,Itemsis[]ConfigItem.error: Execution or parsing error.
Example
result, err := comp.GetConfigStructured()
if err != nil {
log.Fatalf("Failed to get structured config: %v", err)
}
for _, item := range result.Items {
fmt.Printf("%s = %s\n", item.Key, item.Value)
}⚙️ ConfigItem / ConfigResult Types
Struct returned by GetConfigStructured, defined in pkg/composer/result_types.go.
type ConfigItem struct {
Key string `json:"key"`
Value string `json:"value"`
Source string `json:"source,omitempty"`
}
type ConfigResult struct {
Items []ConfigItem `json:"items,omitempty"`
}| Type | Field | Description |
|---|---|---|
ConfigItem | Key | Config item name |
ConfigItem | Value | Config item value |
ConfigItem | Source | Source information (may be empty) |
ConfigResult | Items | List of all config items |
Parsing Logic
ParseConfigList splits the output of composer config --list by lines, and splits each line into Key and Value at the first space. Empty lines are skipped.
📄 Relationship with composer.json File Operations
The config module goes through the composer config subcommand, while the following methods (from composer_json.go) use pure file read/write; the two are complementary:
| Method | Signature | Purpose |
|---|---|---|
ReadComposerJSON | func (c *Composer) ReadComposerJSON() (*ComposerJSON, error) | Read and parse entire composer.json |
WriteComposerJSON | func (c *Composer) WriteComposerJSON(composerJSON *ComposerJSON) error | Write struct back to composer.json |
AddRequire | func (c *Composer) AddRequire(packageName, version string, isDev bool) error | Append dependency to require/require-dev |
AddScript | func (c *Composer) AddScript(name string, script interface{}, description string) error | Add script with optional description |
AddAutoload | func (c *Composer) AddAutoload(type_ string, namespace string, paths interface{}, isDev bool) error | Add autoload rule |
SetConfig | func (c *Composer) SetConfig(key string, value interface{}) error | Set composer.json's config field |
GetConfig | func (c *Composer) GetConfig(key string) (interface{}, error) | Read composer.json's config field |
SetProperty | func (c *Composer) SetProperty(property string, value interface{}) error | Set top-level property (name/description/type, etc.) |
SetConfig vs SetConfigWithGlobal
SetConfig(key, value)(composer_json.go): Directly modifies theconfigfield of thecomposer.jsonfile, does not call composer, value can be anyinterface{}(number, boolean, object).SetConfigWithGlobal(setting, value, global)(config.go, this page): Goes through thecomposer configcommand, value can only bestring, can write globally.
Choose as needed: use the former for batch structured writes, use the latter for single command-style writes.
For full signatures, parameters, examples, and notes on the above methods, see composer.json Operations.
Advanced and Related
- 📄 composer.json Operations: All methods for pure file read/write of
composer.json. - ✅ Validate module: Finer-grained validation variants like
ValidateStrict,ValidateSchema,ValidateComposerLock. - 🧱 Platform module: Platform check capabilities like
CheckPlatform,GetPHPVersion,HasExtension. - 🏗️ Repository module: Methods that modify repository and stability related config via
composer config, likeSetPreferredInstall,SetMinimumStability,SetPreferStable.