Writing command line tools with PHP

Did you know it's possible to create command line tools with PHP, I'll show you how

2 minutes

Writing command line tools with php

Why would you build your own command

We use the commandline a lot, and maybe you have a great idea for building your own command line program. It can be a tool like composer or php artisan , things that make the life of developers easier and are real time savers. So let's go and build that tool, I'll explain you some possibilities.

How to build ?

The most well know way of building command line tools is building the tool with bash scripting, the language of the commandline. That's a possibility if you like it , but I don't prefer it let's figure out why not ...

Why not in bash scripting

For me, it feels much more comfortable to program in PHP, maybe it's because of the lack of knowledge of the language but bash scripting is much more cumbersome to write in than PHP. Php projects can be heavily structured and yeah, it's the language I'm familiar to work in, so it works better for me. I've created Sajan version 1 in bash scripting and to be honest if I open that codebase now I always have to figure out what is does. It's not possible to structure all the logic in classes and services ( as far as I know ), so the bloat grows fast.

The technology to use

You can write your PHP command's in vanilla PHP, but that's not my choice. By using a tool called Ibis, created by Mohammed Said I discovered the symfony console. That's a symfony component built to help you create command line tools. It has a nice Api and provides you with the possibility to use colors, questions, choices , all out of the box.

An example

This is a command created for my open source tool Sajan, it's a command in Sajan to show the ip address of your computer.

I show you an extract of the code but please feel free to take a look in the full source code on GitHub, that will learn you a lot.

In the first section, the configure section you can specify the name of your command, I've set a description and an alias. So this command can be fired by calling sajan ip:lan or sajan il. The command will output something like Your lan ip address is :

You can see this is a fluent way of bash programming using the symfony console component.

setName('ip:lan') ->setDescription('Get your lan ip address') ->setAliases(['il']); } /** * Execute the command. * * @param InputInterface $input * @param OutputInterface $output * @return int */ public function execute(InputInterface $input, OutputInterface $output): int { $ip = Process::fromShellCommandline("ifconfig | grep \"inet \" | grep -Fv | awk '{print $2}'")->mustRun()->getOutput(); $output->writeln('Your lan ip address is : '.trim($ip).' '); return 0; } }

this article has been read 43 times