Developer Blog

  • Blog
  • /
  • Using PHPixie from Command Line
By Dracony on 11 May 2013

Sometimes you may need to run PHPixie from command line to perform various tasks. For example you may want to set up a cron that would tidy up your database every few hours, email you logs or calculate some statistics. To achieve this all we need is an alternative entry point cli.php. An example one would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// /cli.php
$root = __DIR__ ;
$loader = require $root.'/vendor/autoload.php';
$loader->add('', $root.'/classes/');

$pixie = new \App\Pixie();
$pixie->bootstrap($root);
$method = $argv[1];
$params = array_slice($argv,2);

$cli = new \App\CLI($pixie);

//This is to avoid default HTML error rendering
try{
    call_user_func_array(array($cli, $method), $params);
}catch(Exception $e){
    echo 'ERROR: '.$e->getMessage().' in '.$e->getFile().' on line '.$e->getLine();
}

?>

Nw we can have an App\CLI class. First parameter to the command line will determine the method to run. Here is a small example:

1
2
3
4
5
6
7
8
9
10
11
// /classes/App/CLI.php
namespace App;
class CLI {
    public $pixie;
    public function __construct($pixie) {
        $this->pixie = $pixie;
    }
    public function is($name, $type) {
        echo("$name is a $type");
    }
}

Now we can try tunning it:

1
2
> php cli.php is Tinkerbell fairy
Tinkerbell is a fairy
comments powered by Disqus