Pragmatism in the real world

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:

#!/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:

$ bin/run.php hello world

and the output is, as you would expect:

Hello, world

This works by converting the command line parameters into the URL path for Slim to route by imploding $argv with a ‘/’ separator. Slim needs an environment that looks vaguely web-like. This is quite easy to do via the Slim\Environment::mock() method which will set up all the array keys that the framework expects to have access to. It’s used for unit test, but also works really well here. All we need to do is set PATH_INFO to our previously created $pathInfo and Slim can now route.

We also need to stop Slim creating HTML errors, so we set our own closures for notFound and error and we’re done.

The rest of the file is simply setting up the routes we need and then calling run().