PHP

PHP BOOTCAMP: Develop Your Own CLI Scripts


Developers run CLI Scripts every now and then and I bet you have used them severally. I mean Command line/ Shell Scripts.

The Question is:

Have you been able to create yours?

Have you wondered how these things are created?

As a Laravel Developer, have you wondered how php artisan, php artisan <a-type-of-argument> works?

It’s actually very simple. You can write those scripts in virtually any language.

Create a file named cab. Now it shouldn’t have any extension like .txt or .php or any type at all.

cab

#!/usr/bin/env is actually what makes the file a script that can be executed straight from the terminal even without any file extension.

#!/usr/bin/env php specifies the language that the script would be written in.

$argv is PHP’s way of accepting arguments passed to the terminal

$argv is an array

e.g php artisan migrate

$argv[0] is artisan

$argv[1] is migrate

e.g php prosper.php

$argv[o] is prosper.php

$argv[1] will give you a PHP Notice Error about an undefined offset because it does not exist.

From the code we have above, if we run:

We’ll get:

because we didn’t pass in any command.

Awesome!!!

Now, you can see it’s that simple.

You have the knowledge now, So feel free to code up something much more functional and complex.

Check out the source code here

You can check out cool-ascii-faces php package I developed to have fun in the commandline and also learn how to abstract your code into modular components.

Please if you have any questions or observations, feel free to drop it in the comments section below.

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.