A script, in Composer's terms, can either be a PHP callback (defined as a static method) or any command-line executable command. Scripts are useful for executing a package's custom code or package-specific commands during the Composer execution process.
NOTE: Only scripts defined in the root package's composer.json
are
executed. If a dependency of the root package specifies its own scripts,
Composer does not execute those additional scripts.
Composer fires the following named events during its execution process:
install
command is executed.install
command is executed.update
command is executed.update
command is executed.The root JSON object in composer.json
should have a property called
"scripts"
, which contains pairs of named events and each event's
corresponding scripts. An event's scripts can be defined as either as a string
(only for a single script) or an array (for single or multiple scripts.)
For any given event:
Script definition example:
{
"scripts": {
"post-update-cmd": "MyVendor\\MyClass::postUpdate",
"post-package-install": [
"MyVendor\\MyClass::postPackageInstall"
],
"post-install-cmd": [
"MyVendor\\MyClass::warmCache",
"phpunit -c app/"
]
}
}
Using the previous definition example, here's the class MyVendor\MyClass
that might be used to execute the PHP callbacks:
<?php
namespace MyVendor;
use Composer\Script\Event;
class MyClass
{
public static function postUpdate(Event $event)
{
$composer = $event->getComposer();
// do stuff
}
public static function postPackageInstall(Event $event)
{
$installedPackage = $event->getOperation()->getPackage();
// do stuff
}
public static function warmCache(Event $event)
{
// make cache toasty
}
}
When an event is fired, Composer's internal event handler receives a
Composer\Script\Event
object, which is passed as the first argument to your
PHP callback. This Event
object has getters for other contextual objects:
getComposer()
: returns the current instance of Composer\Composer
getName()
: returns the name of the event being fired as a stringgetIO()
: returns the current input/output stream which implements
Composer\IO\IOInterface
for writing to the console