Kotchasan Framework Documentation

Kotchasan Framework Documentation

View Class - Presentation Layer Management

EN 03 Feb 2026 17:02

View Class - Presentation Layer Management

The View class serves as the base for the application's presentation layer. It orchestrates the rendering process by managing templates, HTTP headers, meta tags, and asset injection (CSS/JS).

Namespace

Kotchasan\View

Overview

This class integrates with the Template system to inject data into HTML views and manages the document's <head> section and HTTP response headers.

Key Features

  1. Asset Management: Dynamic injection of CSS files, JavaScript files, and inline scripts into the HTML <head>.
  2. Template Rendering: Replaces placeholders in templates with dynamic content.
  3. Response Control: Manages HTTP headers and final content output.

Public Methods

create()

Factory method to create a View instance.

public static function create(): static

renderHTML()

Process and render the final HTML from a template.

public function renderHTML(string|null $template = null): string

Process:

  • Injects system variables: {WEBTITLE}, {WEBDESCRIPTION}, {WEBURL}, {SKIN}.
  • Injects accumulated Meta tags, CSS, and JS into the <head> section.
  • Performs variable replacement using data set via setContents.

setContents()

Set key-value pairs for template replacement.

public function setContents(array $array): void

Example:

$view->setContents([
    '/{CONTENT}/' => 'Page Content',
    '/{FOOTER}/' => 'Footer Info'
]);

setMetas() / setHeaders()

Set HTML Meta tags and HTTP Headers.

public function setMetas(array $array): void
public function setHeaders(array $array): void

addCSS() / addJavascript() / addScript()

Inject resources into the page.

public function addCSS(string $url): void
public function addJavascript(string $url): void
public function addScript(string $script): void

Data Access Helpers

Safe accessors for arrays and objects with default fallback.

public static function array_value(array $array, string $key, mixed $default = ''): mixed
public static function object_value(object $source, string $key, mixed $default = ''): mixed

back()

Generate a return URL, intelligently handling query strings (e.g., stripping login/logout actions).

public static function back(array|string $f): string

output()

Send headers and echo the content.

public function output(string $content): void

Usage Example

// Initialize View
$view = Kotchasan\View::create();

// Add Assets
$view->addCSS('style.css');
$view->addScript('console.log("Hello");');

// Set Data
$view->setContents([
    '/{TOPIC}/' => 'My Topic',
    '/{DETAIL}/' => 'Details here...'
]);

// Render using 'main' template
echo $view->renderHTML(Template::load('', '', 'main'));

File Size: 263 lines