Skip to content

➕ 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) error

Parameters ​

ParameterTypeDescription
packageNamestringPackage name, e.g. symfony/console
versionstringVersion constraint, e.g. ^5.0
isDevbooltrue writes to require-dev, false writes to require

Return value ​

  • error: Returned when reading or writing composer.json fails.

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 is nil, it is initialized automatically.
  • ⚠️ If the package already exists, the original version constraint is overwritten.
  • 🚀 To actually install dependencies into vendor, use RequirePackage (runs the composer require command). For batch declaration, use RequireMultiple.
  • 🗑️ The corresponding removal method is RemoveRequire.

Released under the MIT License