PHP-CLi basic functions

The following functions can help you quickly get going with a CLi project.

#!/usr/bin/env php
<?php
 
// Clear the terminal screen.
// Using the passthru function to fun the local system's clear command
// returns none
function clearTerm()
{
        passthru('clear');
}
 
// Short wrapper for fwrite
// Permits easier explicit writing to STDOUT
// returns none
function toSTDOUT($string)
{
        fwrite(STDOUT,$string);
}
 
// Output with default prefix and suffix
function sendOutput($output = '> ',$NL=PHP_EOL)
{
        toSTDOUT($output.$NL);
}
 
// New exit allowing simple debugging via var_dump()
// Otherwise exits normally
// returns none
function nuExit($str=0)
{
        clearTerm();
        if(is_array($str))
        {
                var_dump($str);
                exit(0);
        }
        exit($str.PHP_EOL);
}
 
// get a trimmed string from STDIN
// returns a string
function getSTDIN()
{
        return trim(fgets(STDIN));
}
 
// get input with a prompt
// built in quit catching
// returns a string or nothing
function getInput($prompt = "> ", $silent = FALSE)
{
        if( ! $silent) { sendOutput($prompt); }
        $var = getSTDIN();
 
        if('quit' == $var) nuExit('Quit entered at prompt.');
 
        return $var;
}
 
// Check input with regex
// returns boolean
function checkMatch($needle,$haystack)
{
        if(preg_match('/^'.$needle.'$/i',$haystack)) return TRUE;
        return FALSE;
}

Now that we have those in place, something like the following is easy enough.

#!/usr/bin/env php
<?php
 
// include the functions here
include "functions.file.php";
 
clearTerm();
sendOutput('Hi there, welcome to a simple CLi functions tutorials.');
$response = getInput('Have you done this before?');
if( checkMatch('([Yy][Ee]?(?:[Ss]|[Aa])?)',$response) )
{
        nuExit('Okay, bye!');
}
else
{
        sendOutput('Welcome to PHP-CLi.');
        nuExit();
}

That’s it.

Author: Mike on December 18, 2014
Category: PHP, Tutorials
Tags: , , , ,

Comments are closed.

Last articles