Slim 4 - PHP-DI

Daniel Opitz
Daniel Opitz
24 May 2020

Table of contents

Requirements

Introduction

PHP-DI is one of the most used Dependency Injection Container for PHP.

Installation

To install PHP-DI, run:

composer require php-di/php-di

Configuration

Create a file for the container defintions that cannot be autowired, e.g config/container.php:

<?php

use Monolog\Logger;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

return [
    'settings' => function () {
        return require __DIR__ . '/settings.php';
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);

        return AppFactory::create();
    },
    
    // Add more definitions here...
}

Bootrapping

In your config/bootstrap.php or wherever you have your bootrap code:

<?php

use DI\ContainerBuilder;
use Slim\App;

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

$containerBuilder = new ContainerBuilder();

// Add container definitions
$containerBuilder->addDefinitions(__DIR__ . '/container.php');

// Build PHP-DI Container instance
$container = $containerBuilder->build();

// Create App instance
$app = $container->get(App::class);

// Add routes, middleware etc...

$app->run();

Usage

Autowiring

PHI-DI is able to automatically create and inject dependencies into all classes that make use of (constructor) dependency injection. In order to achieve that, PHP-DI uses PHP’s reflection to detect what parameters a constructor needs.

You can read more about autowiring here: Autowiring

Read more