Slim Framework Integration Guide

How to add Tplix to Slim 4 using PHP-DI and inject it into route handlers.

Slim · v4

Tplix + Slim 4

Register Tplix in the PHP-DI container and inject it into route callbacks or action classes.

composer require tplix/tplix php-di/php-di
1

Configure the Container

app/container.php
<?php
use DI\ContainerBuilder;
use Tplix\Tplix;

$builder = new ContainerBuilder();
$builder->addDefinitions([
    Tplix::class => function () {
        $tplix = Tplix::getInstance();
        $tplix->setTemplateDir(__DIR__ . '/../templates');
        $tplix->setCompileDir(__DIR__ . '/../var/tplix_c');
        $tplix->setCacheDir(__DIR__  . '/../var/tplix_cache');
        return $tplix;
    },
]);

return $builder->build();
2

Bootstrap & Define Routes

public/index.php
<?php
use Slim\Factory\AppFactory;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Tplix\Tplix;

$container = require __DIR__ . '/../app/container.php';
AppFactory::setContainer($container);
$app = AppFactory::create();

$app->get('/', function (Request $req, Response $res, Tplix $tplix) {
    $tplix->assign('title', 'Home');
    $tplix->assign('items', getItems());
    $res->getBody()->write($tplix->fetch('home.tpl'));
    return $res;
});

$app->run();