Slim 3 MVC

This post documents a Slim 3 PHP micro framework application with models, views and controllers (MVC) using Twig templates to display data from a database.


* I am using XAMPP on Windows as my web server with URL rewriting.


Clone or download the source code from GitHub.

Source Code

After Composer had been installed, using a command shell, navigate to the directory where the source code has been cloned or extracted to. In the project root is a composer.json package file. This file defines the project requirements. Run the composer require command to install the project dependencies read from the composer.json package configuration into the project.

# install slim and it's dependencies
composer require slim/slim "^3.0"

The included composer.json package file also contains an autoload property for PSR-4 autoloading support in Composer. This will map the App namespace to the relative path specified for the classes.

    "require": {
        "slim/slim": "^3.0",
        "slim/twig-view": "^2.1",
        "php-di/slim-bridge": "^1.0"
    "autoload": {
        "psr-4": {
            "App\\": "src\\classes"

When the map needs to be updated, run composer dump-autoload.

# update and optimize the autoloader
composer dump-autoload -o

There are two versions of this starter application:

  1. tag oobdic - Out of the box dependency injection configuration, uses Slim’s built-in dependency container.
  2. tag phpdi - PHP-DI/Slim-Bridge dependency injection into the controller. This is the latest version of the starter app.

To install PHP-DI/Slim-Bridge in an existing project, require php-di/slim-bridge using composer.

composer require php-di/slim-bridge

Changing the Database Connection String

The connection string is currently set to connect to the SQLite demo.db database which makes it easy to include a database with the project.

\App\Database\DatabaseInterface::class => function (ContainerInterface $container) {
    return new \App\Database\PDODatabase('sqlite:../data/demo.db');

Here is the container definition with the connection string changed for a MySQL database.

\App\Database\DatabaseInterface::class => function (ContainerInterface $container) {
    return new \App\Database\PDODatabase('mysql:host=localhost;dbname=demo', 'username', 'password');
comments powered by Disqus