What is the best way to echo to the console in a composer.json script? For example, I have used the scripts section to create a custom installer and at the end I want to display a message in the console.
At the moment i'm simply doing an echo like this
"scripts": {
"post-update-cmd": [
"clear",
"echo \"\n\nInstallation Complete\""
]
}
This works, but it prints out the command and the echo in the console, so it ends up looking like this.

As composer outputs all of the custom commands that are in the scripts anyway, it doubles up and looks ugly!
Whats the best and cleanest way to use the composer scripts to echo a message to the console?
I just had to do something similar today and didn't feel like writing a whole script/class for this.
I got it working better than I expected by abusing two things:
"scripts": {
"post-update-cmd": [
"# <info>For your info</info>",
"# <comment>A comment</comment>",
"# <error>Error!!!!</error>",
"# <href=https://symfony.com>Symfony Homepage</>"
]
}
Tada!
If you use a PHP class instead of using shell directly for your scripts, you can use Composers' IO system to write to the console.
For example, create a class similar to this:
<?php
declare(strict_types=1);
namespace MyApp\Composer;
use Composer\Script\Event;
class ScriptHandler
{
public static function myScript(Event $event): void
{
// Your script here
}
}
Composer\Script\Event class has a method called getIO() which you can use to get the instance of Composer\IO\IOInterface, which then has a method write, making your myScript method looking something like this:
public static function myScript(Event $event): void
{
$event->getIO()->write('foo'):
}
Finally, to use this class, just reference it in your post-update-cmd:
"scripts": {
"post-update-cmd": [
"MyApp\\Composer\\ScriptHandler::myScript"
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With