Hyperf Integration Guide
How to integrate Tplix with Hyperf 3 on Swoole, with a safe singleton pattern for long-running workers.
Hyperf · v3 · Swoole
Tplix + Hyperf
Register as a DI singleton and clear assigned variables after each request to keep worker state clean in Swoole's persistent processes.
composer require tplix/tplix
1
Register in DI Dependencies
config/autoload/dependencies.php
<?php
use Tplix\Tplix;
return [
Tplix::class => function () {
$tplix = Tplix::getInstance();
$tplix->setTemplateDir(BASE_PATH . '/storage/templates/');
$tplix->setCompileDir(BASE_PATH . '/runtime/tplix_c/');
$tplix->setCacheDir(BASE_PATH . '/runtime/tplix_cache/');
$tplix->caching = 1;
$tplix->debugging = false;
return $tplix;
},
];
2
Use in a Controller
app/Controller/IndexController.php
<?php
namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Tplix\Tplix;
#[Controller]
class IndexController
{
public function __construct(
private Tplix $tplix,
private ResponseInterface $response
) {}
#[GetMapping(path: '/')]
public function index(): ResponseInterface
{
$this->tplix->assign('title', 'Home');
$this->tplix->assign('time', time());
$html = $this->tplix->fetch('index.tpl');
$this->tplix->clearAllAssign(); // clear after each request
return $this->response->raw($html);
}
}
Swoole note: Tplix is a static singleton shared across requests in each worker. Always call
$tplix->clearAllAssign() after fetching your template — or in an after-request middleware — to prevent variable bleed between requests.