🧩 AddScript
Adds a script to the scripts section of composer.json, optionally with a description.
When to use
Use when you need to automatically run commands on lifecycle hooks such as install, update, or test. A Composer script can be a single command string, a PHP callback, or an array of commands. This method only modifies the configuration file; once registered, it can be triggered with composer run-script.
Signature
go
func (c *Composer) AddScript(name string, script interface{}, description string) errorParameters
| Parameter | Type | Description |
|---|---|---|
name | string | Script name, e.g. post-install-cmd or a custom name like test |
script | interface{} | Script content; can be a string, []string, or PHP callback string |
description | string | Script description, optional; when non-empty it is written to the scripts-descriptions section |
Return value
error: Returned when reading or writingcomposer.jsonfails.
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)
}
// Add a single-command script (runs after install)
if err := comp.AddScript(
"post-install-cmd",
"php -r \"echo 'Installation completed!';\"",
"Run after installation",
); err != nil {
log.Fatal(err)
}
// Add a multi-command script
commands := []string{
"php -r \"echo 'Starting tests...';\"",
"phpunit",
}
if err := comp.AddScript("test", commands, "Run tests"); err != nil {
log.Fatal(err)
}
}Advanced
- 🔄 Internal flow:
ReadComposerJSON→ writeScripts[name]→ optionally writeScriptsDescriptions[name]→WriteComposerJSON. - ⚠️ If a script with the same name already exists, it is overwritten.
- 🏃 To actually run a registered script, see
RunScript/ExecuteScript; to list scripts, seeListScripts. - 🗑️ The corresponding removal method is
RemoveScript.