Run Slim 2 from the command line
If you need to run a Slim Framework 2 application from the command line then you need a separate script from your web-facing index.php. Let's call it bin/run.php: bin/run.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
#!/usr/bin/env php <php chdir(dirname(__DIR__)); // set directory to root require 'vendor/autoload.php'; // composer autoload // convert all the command line arguments into a URL $argv = $GLOBALS['argv']; array_shift($GLOBALS['argv']); $pathInfo = '/' . implode('/', $argv); // Create our app instance $app = new Slim\Slim([ 'debug' => false, // Turn off Slim's own PrettyExceptions ]); // Set up the environment so that Slim can route $app->environment = Slim\Environment::mock([ 'PATH_INFO' => $pathInfo ]); // CLI-compatible not found error handler $app->notFound(function () use ($app) { $url = $app->environment['PATH_INFO']; echo "Error: Cannot route to $url"; $app->stop(); }); // Format errors for CLI $app->error(function (\Exception $e) use ($app) { echo $e; $app->stop(); }); // routes - as per normal - no HTML though! $app->get('/hello/:name', function ($name) { echo "Hello, $name\n"; }); // run! $app->run(); |
We set the script to be excutable and then we can then run it like this:
1 |
$ bin/run.php hello world |
and the output is, as you would expect:
1 |
<strong></strong>Hello, world |
This works by converting the command line parameters into the URL path for Slim to route by imploding $argv… continue reading.