Files
scoutiq/app/Controllers/Controller.php
2026-06-05 16:08:53 +03:00

66 lines
1.7 KiB
PHP

<?php
namespace App\Controllers;
use App\Core\App;
use App\Core\Session;
abstract class Controller
{
protected Session $session;
public function __construct()
{
$this->session = App::$app->session;
}
/**
* Render a view within a layout.
*/
protected function render(string $view, array $data = [], string $layout = 'app'): string
{
$viewFile = __DIR__ . "/../../resources/views/{$view}.php";
if (!file_exists($viewFile)) {
throw new \Exception("View template {$view} not found.");
}
// Automatically inject current language, translation array, and authenticated user
$lang = $this->session->get('lang', 'en');
$langFile = __DIR__ . "/../../resources/lang/{$lang}.php";
$t = file_exists($langFile) ? require $langFile : [];
$user = \App\Core\App::$app->request->routeParam('_authenticated_user');
$data = array_merge([
'lang' => $lang,
't' => $t,
'user' => $user,
], $data);
// Extract variables to local scope
extract($data);
// Capture inner view content
ob_start();
include $viewFile;
$content = ob_get_clean();
// Capture layout content wrapping the inner view
$layoutFile = __DIR__ . "/../../resources/views/layouts/{$layout}.php";
if (!file_exists($layoutFile)) {
return $content;
}
ob_start();
include $layoutFile;
return ob_get_clean();
}
/**
* Escape string values for rendering safely.
*/
protected function escape(mixed $data): string
{
return htmlspecialchars((string)$data, ENT_QUOTES, 'UTF-8');
}
}