Kotchasan Framework Documentation
Kotchasan\View
Kotchasan\View
View is the class responsible for managing the presentation layer in the MVC pattern, handling HTML generation and template management.
Table of Contents
- Overview
- Installation and Setup
- Core Methods
- Usage Examples
- Best Practices
- Common Mistakes
- Related Classes
Overview
The View class is a crucial component of the Kotchasan Framework that handles:
- Template Management: Manages HTML templates and content replacement using regex patterns
- Asset Management: Manages CSS, JavaScript files, and meta tags
- Content Rendering: Creates complete HTML output from templates
- Header Management: Controls HTTP headers and responses
- Script Integration: Adds JavaScript files and inline scripts
When to use:
- When generating HTML pages in MVC controller
- When building email templates
- When creating dynamic content with template placeholders
- When managing page assets (CSS/JS) programmatically
Installation and Setup
Requirements
- PHP 7.4 or higher
- Kot chasan Framework
- HTML template files (.html)
Basic Setup
use Kotchasan\View;
// Create view instance
$view = View::create();The View class automatically initializes with these default values in templates:
/{WEBTITLE}/- Site title from configuration/{WEBDESCRIPTION}/- Site description from configuration/{WEBURL}/- Website base URL/{SKIN}/- Current template/skin path
Core Methods
create()
Creates a new View instance (Factory method).
Signature:
public static function create(): staticReturns: View instance
Example:
$view = View::create();setContents()
Sets content placeholders for template replacement.
Signature:
public function setContents(array $array): voidParameters:
$array(array) - Key-value pairs where keys are patterns (e.g.,'/{NAME}/') and values are replacement strings
Example:
$view->setContents([
'/{TITLE}/' => 'Page Title',
'/{CONTENT}/' => 'Page content here',
'/{COPYRIGHT}/' => '© 2024 My Website'
]);setContentsAfter()
Sets content to be replaced AFTER the template is rendered. Useful for final modifications.
Signature:
public function setContentsAfter(array $array): voidParameters:
$array(array) - Key-value pairs for post-rendering replacement
Example:
$view->setContentsAfter([
'/{FINAL_SCRIPT}/' => '<script>console.log("Page loaded");</script>'
]);addCSS()
Adds a CSS file link to the HTML head.
Signature:
public function addCSS(string $url): voidParameters:
$url(string) - URL or path to the CSS file
Example:
$view->addCSS('/css/bootstrap.min.css');
$view->addCSS('/css/custom.css');Generated HTML:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/custom.css">addJavascript()
Adds a JavaScript file to the HTML head.
Signature:
public function addJavascript(string $url): voidParameters:
$url(string) - URL or path to the JavaScript file
Example:
$view->addJavascript('/js/jquery.min.js');
$view->addJavascript('/js/app.js');Generated HTML:
<script src="/js/jquery.min.js"></script>
<script src="/js/app.js"></script>addScript()
Adds inline JavaScript code to be inserted in the head section.
Signature:
public function addScript(string $script): voidParameters:
$script(string) - JavaScript code (without<script>tags)
Example:
$view->addScript('
$(document).ready(function() {
console.log("Page ready");
});
');Generated HTML:
<script>
$(document).ready(function() {
console.log("Page ready");
});
</script>setHeaders ()
Sets HTTP headers for the response.
Signature:
public function setHeaders(array $array): voidParameters:
$array(array) - Key-value pairs of header names and values
Example:
$view->setHeaders([
'Content-Type' => 'text/html; charset=utf-8',
'X-Frame-Options' => 'DENY',
'X-Content-Type-Options' => 'nosniff'
]);setMetas()
Adds custom meta tags to the HTML head.
Signature:
public function setMetas(array $array): voidParameters:
$array(array) - Key-value pairs where values are complete meta tag HTML
Example:
$view->setMetas([
'description' => '<meta name="description" content="Website description">',
'keywords' => '<meta name="keywords" content="keyword1, keyword2">',
'og:title' => '<meta property="og:title" content="Page Title">'
]);renderHTML()
Renders the final HTML output by processing the template with all set content.
Signature:
public function renderHTML(?string $template = null): stringParameters:
$template(string|null) - Template content or null to use 'index.html' from Template::load()
Returns: string - The rendered HTML
Example:
// Use default template (index.html)
$html = $view->renderHTML();
// Use custom template content
$template = '<html><head>{/TITLE/}</head><body>{/CONTENT/}</body></html>';
$html = $view->renderHTML($template);output()
Sends HTTP headers and outputs the content to the browser.
Signature:
public function output(string $content): voidParameters:
$content(string) - The content to output
Example:
$html = $view->renderHTML();
$view->output($html);back()
Creates a URL for navigation, preserving query string parameters from current request.
Signature:
public static function back(array|string $f): stringParameters:
$f(array|string) - Query string or parameter modifications
Returns: string - Modified URL
Note: Requires active HTTP request context (Request object must be initialized)
Example:
// In a controller with active request
$backUrl = View::back('module=home&action=index');
// Returns: current URL with modified/added parametersarray_value()
Safely retrieves a value from an array with a default fallback.
Signature:
public static function array_value(array $array, string $key, mixed $default = ''): mixedParameters:
$array(array) - The source array$key(string) - The key to retrieve$default(mixed) - Default value if key doesn't exist (default: '')
Returns: mixed - The value or default
Example:
$data = ['name' => 'John', 'age' => 30];
$name = View::array_value($data, 'name', 'Anonymous'); // Returns: 'John'
$city = View::array_value($data, 'city', 'Unknown'); // Returns: 'Unknown'object_value()
Safely retrieves a property value from an object with a default fallback.
Signature:
public static function object_value(object $source, string $key, mixed $default = ''): mixedParameters:
$source(object) - The source object$key(string) - The property name to retrieve$default(mixed) - Default value if property doesn't exist (default: '')
Returns: mixed - The property value or default
Example:
$user = (object)['name' => 'Jane', 'email' => 'jane@example.com'];
$name = View::object_value($user, 'name', 'Anonymous'); // Returns: 'Jane'
$phone = View::object_value($user, 'phone', 'N/A'); // Returns: 'N/A'Usage Examples
1. Basic Page Rendering
use Kotchasan\View;
class HomeController
{
public function index()
{
// Create view
$view = View::create();
// Set page content
$view->setContents([
'/{TITLE}/' => 'Welcome to Our Website',
'/{HEADING}/' => 'Welcome!',
'/{CONTENT}/' => 'This is the homepage content.',
'/{YEAR}/' => date('Y')
]);
// Add CSS
$view->addCSS('/css/style.css');
// Add JavaScript
$view->addJavascript('/js/main.js');
// Render and output
$html = $view->renderHTML();
$view->output($html);
}
}2. Product Detail Page
use Kotchasan\View;
class ProductController
{
public function show($id)
{
// Fetch product data
$product = $this->getProduct($id);
// Create view
$view = View::create();
// Set content
$view->setContents([
'/{TITLE}/' => $product->name . ' - Our Store',
'/{PRODUCT_NAME}/' => htmlspecialchars($product->name),
'/{PRODUCT_PRICE}/' => number_format($product->price, 2),
'/{PRODUCT_DESCRIPTION}/' => nl2br(htmlspecialchars($product->description)),
'/{PRODUCT_IMAGE}/' => '<img src="'.$product->image.'" alt="'.htmlspecialchars($product->name).'">'
]);
// Add product-specific assets
$view->addCSS('/css/product.css');
$view->addJavascript('/js/product-gallery.js');
// Add structured data for SEO
$view->addScript('
var productData = {
id: '.$product->id.',
name: "'.addslashes($product->name).'",
price: '.$product->price.'
};
');
return $view->renderHTML();
}
}3. SEO-Optimized Page
$view = View::create();
// Set page content
$view->setContents([
'/{TITLE}/' => 'Top Products 2024 - Best Deals',
'/{CONTENT}/' => $pageContent
]);
// Add comprehensive SEO meta tags
$view->setMetas([
'description' => '<meta name="description" content="Find the best products with amazing deals in 2024">',
'keywords' => '<meta name="keywords" content="products, deals, 2024, shopping">',
'og:title' => '<meta property="og:title" content="Top Products 2024">',
'og:description' => '<meta property="og:description" content="Find the best products">',
'og:image' => '<meta property="og:image" content="https://example.com/image.jpg">',
'og:url' => '<meta property="og:url" content="https://example.com/products">',
'canonical' => '<link rel="canonical" href="https://example.com/products">'
]);
// Add security headers
$view->setHeaders([
'X-Frame-Options' => 'SAMEORIGIN',
'X-Content-Type-Options' => 'nosniff',
'X-XSS-Protection' => '1; mode=block'
]);
$html = $view->renderHTML();4. Email Template
use Kotchasan\View;
class EmailService
{
public function sendWelcomeEmail($user)
{
$view = View::create();
// Set email template content
$view->setContents([
'/{USER_NAME}/' => htmlspecialchars($user->name),
'/{USER_EMAIL}/' => htmlspecialchars($user->email),
'/{ACTIVATION_LINK}/' => $this->generateActivationLink($user),
'/{WEBSITE_NAME}/' => 'Our Website',
'/{WEBSITE_URL}/' => 'https://example.com',
'/{SUPPORT_EMAIL}/' => 'support@example.com'
]);
// Load email template
$template = file_get_contents(ROOT_PATH.'templates/emails/welcome.html');
$emailHTML = $view->renderHTML($template);
// Send email
mail($user->email, 'Welcome!', $emailHTML, 'Content-Type: text/html');
}
}5. AJAX JSON Response with HTML
use Kotchasan\View;
class CommentController
{
public function add()
{
try {
// Save comment
$comment = $this->saveComment($_POST);
// Generate HTML for the new comment
$view = View::create();
$view->setContents([
'/{COMMENT_ID}/' => $comment->id,
'/{AUTHOR_NAME}/' => htmlspecialchars($comment->author_name),
'/{COMMENT_TEXT}/' => nl2br(htmlspecialchars($comment->text)),
'/{COMMENT_DATE}/' => date('M d, Y H:i', strtotime($comment->created_at))
]);
$template = file_get_contents(ROOT_PATH.'templates/comment-item.html');
$commentHTML = $view->renderHTML($template);
// Return JSON with HTML
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'html' => $commentHTML,
'message' => 'Comment added successfully'
]);
} catch (Exception $e) {
header('Content-Type: application/json', true, 400);
echo json_encode([
'success' => false,
'message' => $e->getMessage()
]);
}
}
}Best Practices
1. Template Organization
// Organize templates by purpose
// templates/
// ├── layouts/
// │ ├── main.html
// │ └── admin.html
// ├── pages/
// │ ├── home.html
// │ └── about.html
// ├── emails/
// │ └── welcome.html
// └── partials/
// ├── header.html
// └── footer.html2. Security: Always Escape User Input
// ✅ GOOD: Escape user input
$view->setContents([
'/{USER_NAME}/' => htmlspecialchars($userName, ENT_QUOTES, 'UTF-8'),
'/{SAFE_HTML}/' => $trustedContent // Only for trusted content
]);
// ❌ BAD: Direct user input
$view->setContents([
'/{USER_NAME}/' => $_POST['name'] // XSS vulnerability!
]);3. Performance: Minimize Assets
// ✅ GOOD: Use combined/minified files
$view->addCSS('/css/combined.min.css');
$view->addJavascript('/js/combined.min.js');
// ❌ BAD: Too many individual files
$view->addCSS('/css/bootstrap.css');
$view->addCSS('/css/font-awesome.css');
$view->addCSS('/css/custom.css');
$view->addCSS('/css/responsive.css');
// ... (multiple HTTP requests)4. Asset Versioning for Cache Busting
$version = '1.2.5'; // Update when files change
$view->addCSS('/css/app.css?v=' . $version);
$view->addJavascript('/js/app.js?v=' . $version);5. Separate Concerns
// ✅ GOOD: Controller prepares data, View renders
class ProductController
{
public function show($id)
{
// Business logic
$product = $this->productService->getById($id);
$relatedProducts = $this->productService->getRelated($id);
// View rendering
return $this->renderProductView($product, $relatedProducts);
}
private function renderProductView($product, $related)
{
$view = View::create();
// ... set contents
return $view->renderHTML();
}
}
// ❌ BAD: Mixed concerns
class ProductController
{
public function show($id)
{
$view = View::create();
$product = DB::table('products')->find($id); // Business logic in view method
$view->setContents(['/{NAME}/' => $product->name]);
return $view->renderHTML();
}
}Common Mistakes
❌ Mistake 1: Not Escaping User Input
// WRONG - XSS vulnerability
$view->setContents([
'/{COMMENT}/' => $_POST['comment']
]);
// CORRECT
$view->setContents([
'/{COMMENT}/' => htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8')
]);❌ Mistake 2: Wrong Pattern Format
// WRONG - Missing regex delimiters
$view->setContents([
'{TITLE}' => 'My Title' // Won't work!
]);
// CORRECT - Use regex pattern format
$view->setContents([
'/{TITLE}/' => 'My Title'
]);❌ Mistake 3: Forgetting to Render
// WRONG - Nothing will be output
$view = View::create();
$view->setContents(['/{TITLE}/' => 'Test']);
// Missing: $view->renderHTML()
// CORRECT
$view = View::create();
$view->setContents(['/{TITLE}/' => 'Test']);
$html = $view->renderHTML();
$view->output($html);❌ Mistake 4: Headers After Output
// WRONG - Headers must be set before any output
echo "Something";
$view->setHeaders(['Content-Type' => 'application/json']); // Too late!
// CORRECT - Set headers first
$view = View::create();
$view->setHeaders(['Content-Type' => 'text/html; charset=utf-8']);
$html = $view->renderHTML();
$view->output($html);Related Classes
- Template - Template loading and processing engine
- Controller - MVC controller base class
- Database - Database operations for dynamic content
Additional Notes
💡 Tip: The View class uses regex-based replacement. Patterns like
/{NAME}/are replaced usingpreg_replace(). Make sure your patterns are valid regex patterns.⚠️ Warning: The
back()method requires an active HTTP request context. It will fail if called outside of a web request (e.g., in CLI scripts).ℹ️ Note: All CSS and JavaScript added via
addCSS()andaddJavascript()are automatically inserted before the closing</head>tag duringrenderHTML().