PHP Command Line rocks

Submitted by pure-php on Sun, 2005-03-13 15:19.

Recently I wrote a PHP Command line app, I was amazed, how easy it was, to write command line app in PHP, and it really rocks.

Here is very simple Command Line handler class, it may be usefull for your apps.

<?php
class CliHandler{
    private 
$in;
    private 
$out;
    private 
$handler;
    public function 
CliHandler($handler){
        
$this->in fopen("php://stdin","r");
        
$this->out fopen("php://stdout""w");
        if(
is_object($handler)){
            
$this->handler $handler;
        }
    }    
    public function 
run(){
        
$str "Try these commands:\n"
        
.implode("\n",get_class_methods($this->handler));
        
$this->out($str);
        while(
$line rtrim(fgets($this->in1024))){
            if(
method_exists($this->handler,$line)){
                
$out $this->handler->$line();
                if(
$out){
                    
$this->out($out);
                }
            }
        }
    }
    public function 
out($str){
        
fwrite($this->out,$str."\n");
    }
}
class 
AnyClass{
    public function 
start(){
        return 
"started";
    }
    public function 
stop(){
        return 
"stoppded";
    }
}
$cli = new CliHandler(new AnyClass());
$cli->run();
?>

CliHandler accepts any class als argument.
Try this.

/usr/local/php/PHP5 CliHandler.class.php
output: Try these command:
start
stop
enter "start"
output: started

add new comment
Submitted by Tom (not verified) on Fri, 2005-05-20 17:04.

if you want to create console apps, just download and install Python from http://www.python.org.

it's as easy as:

print "Hello World"
raw_input('press Return>')

and line 2 is optional ;-)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Datenschutz | Impressum