➕ AddRequire
Adds a dependency package to composer.json, writing to either the require or require-dev section depending on isDev.
When to use
Use when you need to declare project dependencies programmatically. Compared to running the composer require command, this method only modifies the composer.json file itself and does not trigger an actual install, making it suitable for batch generation or templated project configuration.
Signature
go
func (c *Composer) AddRequire(packageName, version string, isDev bool) errorParameters
| Parameter | Type | Description |
|---|---|---|
packageName | string | Package name, e.g. symfony/console |
version | string | Version constraint, e.g. ^5.0 |
isDev | bool | true writes to require-dev, false writes to require |
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 production dependency
if err := comp.AddRequire("symfony/console", "^5.0", false); err != nil {
log.Fatal(err)
}
// Add a development dependency
if err := comp.AddRequire("phpunit/phpunit", "^9.0", true); err != nil {
log.Fatal(err)
}
}Advanced
- 🔄 Internal flow:
ReadComposerJSON→ modify the map →WriteComposerJSON; if the corresponding map isnil, it is initialized automatically. - ⚠️ If the package already exists, the original version constraint is overwritten.
- 🚀 To actually install dependencies into
vendor, useRequirePackage(runs thecomposer requirecommand). For batch declaration, useRequireMultiple. - 🗑️ The corresponding removal method is
RemoveRequire.