We were fortunate to have Josh Lockhart (a.k.a. @codeguy) join us at tonight's UpstatePHP meet-up. He is the creator of Slim Framework and author of Modern PHP (should be in your library) / PHP the Right Way (should be in your bookmarks), which basically makes him a leader of the PHP renaissance.

I loved PHP the Right Way but hadn't heard of Slim yet, so it was great to hear him present the upcoming 3.x version this evening.

Slim currently describes itself as "a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs." Slim provides you with an intelligent router to handle incoming HTTP requests. It implements HTTP request and response objects according to PSR-7 and manages a simple first-in-first-out stack for each route (made up of "middleware" callbacks and the route's own callback) that it invokes in turn to generate a response.

I'm easily distracted by new things, so I couldn't wait to get home and put together a quick "Hello, world!" application using Slim 3.x.

To get started, I created a quick local project directory (yep, slimjim ), changed into it, and grabbed the framework and its dependencies using Composer:

composer require slim/slim:3.x-dev

I then created a small index.php file that includes Composer's autoload file, instantiates a new Slim application object, and registered a simple GET request route. Routes require two parameters, a URI pattern (that may include argument tokens) and a PHP callable that accepts request, response, and argument parameters.

Here I've used a simple closure that echoes the greeting:

<?php

require 'vendor/autoload.php' ;



$app = new \ Slim \ App ();



$app -> get ( '/' , function( $request , $response , $args ) {

echo 'Hello, world!' ;

});



$app -> run ();

?>

To test it out, I fired up PHP's built in web server:

php -S localhost:8000

And then navigated to http://localhost:8000 to see my handsome message.

I made a backwards compatibility inspired gaffe on purpose in my first test by echoing the output directly. In Slim 3.x, your callback is really supposed to write output through the response object and return it instead. It still supports the echo method from previous versions through some ob_start() trickery, but you really should stop doing that and write better code like so:

<?php

require 'vendor/autoload.php' ;



$app = new \ Slim \ App ();



$app -> get ( '/' , function( Slim \ Http \ Request $request , Slim \ Http \ Response $response , array $args ) {

$response -> write ( 'Hello, world!' );

return $response ;

});



$app -> run ();

?>

Note that I'm also a recent phpStorm adoptee, so type hinting my closure's parameters makes for a much nicer development experience. Time to step up!

I look forward to playing with Slim some more.