slim Getting started with slim Installation or Setup


Example

Recommended way to install Slim framework is by using composer.

  1. Create an empty directory

This directory will contain all required files for our Slim application to run. We call this directory root directory so we can address all other application files and directories relative to root directory.

mkdir slim-app
  1. Install Slim framework and its requirements using composer
cd slim-app
composer require slim/slim "^3.0"

From now on, we assume this is our working directory.

After composer finishes downloading required files, there should be two files composer.json and composer.lock and a directory named vendor which includes files downloaded by composer. Now we're ready to create our application. To organize our application, we create another directory:

mkdir public

We call this the public directory and we're going to tell our web server to server our application from this directory.

  1. Sample "Hello World" application

To use Slim create an index.php in public directory with following code:

public/index.php

<?php

include "../vendor/autoload.php";

$app = new \Slim\App();

$app->get('/', function ($request, $response, $args) {
    $response->getBody()->write("Hello world!");
});

$app->run();
  1. Start PHP built in server

We can now use PHP built in server to serve our application:

php -S localhost:8080 -t public

and run project by opening this address in a web browser:

http://localhost:8080

Output

Hello world!

Now configure the webserver so that all requests are passed to this file:

Apache configuration for clean URLs (Optional)

This is not required but recommended for slim projects to remove index.php in API URL.

Create .htaccess in the same folder where your index.php is located. The file should contain the following code:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Make sure your Apache virtual host is configured with the AllowOverride option so that the .htaccess declared rewrite rules can actually be used:

AllowOverride All

Ngnix configuration

TBA