Web Server config and Slim Bootstrapping

Table of contents

Loading...

Introduction

The default entry point for any PHP application is the public/index.php file. This is our front controller where the framework is initialized.

In order for the requests to be directed to the index file in the public directory, the web server needs to be configured.

Web server configuration

With Apache, this is done in the .htaccess file at the root of the project.
The following will redirect all requests to the public/ directory.

File: .htaccess

# Turn on the rewrite engine
RewriteEngine on
# If the URL path is empty, rewrite to the 'public/' directory
RewriteRule ^$ public/ [L]
# For any requested URL path, rewrite to the 'public/' directory followed by the requested path
RewriteRule (.*) public/$1 [L]

Inside the public directory we have to create another .htaccess file to direct requests to the index.php file.

File: public/.htaccess

# Turn on the rewrite engine
RewriteEngine on
# If the requested filename is not a directory
RewriteCond %{REQUEST_FILENAME} !-d
# And if the requested filename is not a file
RewriteCond %{REQUEST_FILENAME} !-f
# Rewrite all requests to index.php with the [QSA] flag to append the query string 
# and [L] flag to stop further processing
RewriteRule ^ index.php [QSA,L]

More info and Nginx configuration in the Slim 4 documentation.

Slim Bootstrapping

In the front-controller index.php the bootstrapping file is loaded.

File: public/index.php

$app = require __DIR__ . '/../config/bootstrap.php';

$app->run();

Bootstrapping is the process of setting up the minimal and necessary configuration for the application to run.

This involves requiring the autoloader, which makes all the classes and dependencies available, setting up the dependency container and requiring the key App::class from the container which essentially initializes the app by creating a Slim\App instance, registering routes and middlewares.

File: config/bootstrap.php

require __DIR__ . '/../vendor/autoload.php';

// Instantiate DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
// Add container definitions and build DI container
$container = $containerBuilder->addDefinitions(__DIR__ . '/container.php')->build();
// Create app instance
return $container->get(App::class);

The app instance is created in the container.

File: config/container.php

use Slim\App;
use Psr\Container\ContainerInterface;
use Slim\Factory\AppFactory;

return [
    App::class => function (ContainerInterface $container) {
        $app = AppFactory::createFromContainer($container);
        // Register routes
        (require __DIR__ . '/routes.php')($app);
        // Register middlewares
        (require __DIR__ . '/middleware.php')($app);
        return $app;
    },

    // ...
];
^