DEV Community

Cover image for Introducting command-builder
Anwar
Anwar

Posted on

Introducting command-builder

I am very happy to announce my newest package for PHP: command-builder.

It helps with creating an executable string, using an object-oriented/fluent style.

// before
$command = "grep -r /var/log/apache2/error.log -e 404";
$output = shell_exec($command);

// after
$command = new Command("grep");
$command->option("r", "/var/log/apache2/error.log")
  ->option("e", "404");

$output = shell_exec($command);
Enter fullscreen mode Exit fullscreen mode

This is very helpful when you wanna create a service around a command, and need to conditionnally add arguments/options/flags.

Actually I needed this for another cool open source package I am about to start, I hope it can help some of you as well!

Installation

To install it, nothing special! You do like you are used to do with others packages:

composer require khalyomede/command-builder
Enter fullscreen mode Exit fullscreen mode

Then, just grab the namespace on your file, and create a new instance of your command.

// index.php

use Khalyomede\CommandBuilder\Command;

require __DIR__ . "/vendor/autoload.php";

$command = new Command("grep");

// ...
Enter fullscreen mode Exit fullscreen mode

Usage

Find all the possibles features, including checking if a flag or an option has been added, in the documentation.

If you need anything, have a suggestion, or something I can help on, please let me know in the comments section down below, or open an issue if you think it can help the package users!

Happy command building 😎

Top comments (5)

Collapse
 
suckup_de profile image
Lars Moelleken

Hi, thanks for this library. Very good idea. 💡 Maybe you should add escapeshellarg for the arguments: github.com/php/php-src/blob/master...

Collapse
 
anwar_nairi profile image
Anwar • Edited

Amazing, that will save me from escaping by hand! Thanks a lot for sharing!

Track the progress of the issue here

github.com/khalyomede/command-buil...

Collapse
 
suckup_de profile image
Lars Moelleken

Next step add a wrapper method for shell_exec and disallow shell_exec via e.g. php code sniffer, so that everybody in the project need to use command-builder with auto-escaping. === more secure 🔐

Thread Thread
 
anwar_nairi profile image
Anwar • Edited

Nice, I need to get some PoC for this, I will see if I can have something for php-cs-fixer (the one I use the most), thanks a lot for this great input Lars!!

Collapse
 
Sloan, the sloth mascot
Comment deleted