Laravel Integration Guide

How to integrate the Tplix template engine with Laravel 9, 10, and 11 using a service provider and dependency injection.

Laravel · v9 / v10 / v11

Tplix + Laravel

Register Tplix as a singleton in a service provider and inject it via Laravel's DI container.

composer require tplix/tplix
1

Create the Service Provider

Create app/Providers/TplixServiceProvider.php and register Tplix as a singleton so Laravel only instantiates it once per request.

app/Providers/TplixServiceProvider.php
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Tplix\Tplix;

class TplixServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Tplix::class, function () {
            $tplix = Tplix::getInstance();
            $tplix->setTemplateDir(resource_path('views/tplix'));
            $tplix->setCompileDir(storage_path('framework/views/tplix_c'));
            $tplix->setCacheDir(storage_path('framework/cache/tplix'));
            $tplix->debugging = app()->isLocal();
            return $tplix;
        });
    }
}
Add App\Providers\TplixServiceProvider::class to the providers array in config/app.php.
2

Use in a Controller

Type-hint Tplix in your controller method and Laravel injects the registered singleton automatically.

app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;

use Tplix\Tplix;

class HomeController extends Controller
{
    public function index(Tplix $tplix)
    {
        $tplix->assign('title', 'Welcome');
        $tplix->assign('user',  auth()->user());
        $tplix->assign('posts', Post::latest()->take(10)->get()->toArray());

        return response($tplix->fetch('home.tpl'));
    }
}