Creating a new SlimPHP application

30 Jan 2017 in Tech

Whilst working with Martin, I've been using the Slim framework for the first time. I usually reach straight for Silex, so trying a similar (yet different) framework has been an interesting experience.

This is the first in a series of posts of how Martin and I built up our project architecture for a Slim application step by step. To follow along you'll need Composer installed

The first thing to do is to bootstrap a project by creating a composer.json and installing Slim itself:

bash
composer init --name you/slim-demo --description "A demo slim project" --author "You <[email protected]>" --type project --require "slim/slim:^3.7" --license MIT -n
composer install

Once you have Slim, the next thing to do is to create your initial route. To to this, create a file called index.php inside a folder called public

bash
mkdir public
touch public/index.php

Add the following content to public/index.php - it's a slightly modified version of the code in the documentation:

php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require __DIR__.'/../vendor/autoload.php';
$container = new \Slim\Container;
$container['settings']['displayErrorDetails'] = true;
$app = new \Slim\App($container);
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write("Hello World");
return $response;
});
$app->run();

The only changes I made were to add a container and enable displayErrorDetails, which makes it easier to see any errors that occur.

In the same folder as composer.json, run php -t public -S localhost:8000 to spin up the built in PHP server, then visit http://localhost:8000 in a browser to see the page. Congratulations, you just created your first SlimPHP application!

You can find the code for this section on GitHub