Say Hello World with Slim

This tutorial demonstrates the typical process for writing a Slim Framework for PHP 5 web application. The Slim Framework for PHP 5 uses the front controller pattern to send all HTTP requests through a single file — usually index.php. By default, Slim comes with a .htaccess file for use with the Apache web server. In the index.php file you require the Slim library file, define routes, and run the Slim application.

Step 1: Require the Slim Framework for PHP 5

First, require the Slim Framework for PHP 5 into your index.php file. Change the file path if necessary.

require 'Slim/Slim.php';

Step 2: Initialize the Slim Framework for PHP 5

Second, instantiate a Slim application. Provide an optional array of settings to configure the application.

//With default settings
$app = new Slim();

//With custom settings
$app = new Slim(array(
    'log.enable' => true,
    'log.path' => './logs',
    'log.level' => 4,
    'view' => 'MyCustomViewClassName'
));

Step 3: Define Routes

Third, define the application’s routes with the methods shown in the example below.

I recommend PHP >= 5.3 to enjoy Slim’s support for anonymous functions. If using a lesser PHP version, the final argument may be anything that returns true for is_callable().

//GET route
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});

//POST route
$app->post('/person', function () {
    //Create new Person
});

//PUT route
$app->put('/person/:id', function ($id) {
    //Update Person identified by $id
});

//DELETE route
$app->delete('/person/:id', function ($id) {
    //Delete Person identified by $id
});

Step 4: Run the Application

Finally, run the Slim Framework for PHP 5 web application. This will usually be the final statement executed in the index.php file.

$app->run();