Kotchasan Framework Documentation
Kotchasan\Controller
Kotchasan\Controller
Controller is the base class for creating Controllers in the Kotchasan Framework's MVC system, serving as the control point for application processing.
Table of Contents
Overview
The Controller class is a base class used for creating Controllers in the Kotchasan Framework's MVC (Model-View-Controller) system. It handles:
- Request and Response Management: Receives and processes HTTP requests
- Model and View Connection: Acts as intermediary between business logic and presentation layer
- Flow Control: Manages application workflow
- Data Management: Prepares data for sending to Views
Installation and Setup
Requirements
- PHP 7.4 or higher
- Kotchasan Framework
- Autoloader configuration
Creating a Controller
use Kotchasan\Controller;
// Create Controller by inheritance
class UserController extends Controller
{
public function index()
{
// Logic for index page
return "Welcome to User Controller";
}
public function show($id)
{
// Logic for displaying user data
return "User ID: " . $id;
}
}Core Methods
create()
Creates a new instance of the Controller
Signature:
class ExampleClass {
<?php
public static function create(): static;
}Usage:
// Create new instance
$controller = Controller::create();
// Or use with child class
$userController = UserController::create();Example:
class ProductController extends Controller
{
public function listProducts()
{
// Create controller instance
$controller = self::create();
// Get product data
$products = $this->getProducts();
// Send data to view
return $this->render('products/list', [
'products' => $products
]);
}
}Usage Examples
1. Basic Controller
use Kotchasan\Controller;
use Kotchasan\View;
class HomeController extends Controller
{
/
Website homepage
/
public function index()
{
// Create view
$view = View::create();
// Set title
$view->setContents([
'/{TITLE}/' => 'Homepage',
'/{CONTENT}/' => 'Welcome to our website'
]);
// Render HTML
return $view->renderHTML();
}
}2. Controller with Database Integration
use Kotchasan\Controller;
use Kotchasan\Database;
use Kotchasan\Http\Request;
class ArticleController extends Controller
{
/
Display article list
/
public function index(Request $request)
{
// Get data from database
$db = Kotchasan\Database::create();
$articles = $db->select()
->from('articles')
->where(['status', 1])
->order('created_at DESC')
->limit(10)
->toArray();
// Send data to view
$view = View::create();
$view->setContents([
'/{TITLE}/' => 'All Articles',
'/{ARTICLES}/' => $this->renderArticleList($articles)
]);
return $view->renderHTML();
}
/
Display single article
/
public function show(Request $request)
{
$id = $request->get('id')->toInt();
// Find article
$db = Kotchasan\Database::create();
$article = $db->select()
->from('articles')
->where(['id', $id], ['status', 1])
->first();
if (!$article) {
throw new \Exception('Article not found', 404);
}
// Display article
$view = View::create();
$view->setContents([
'/{TITLE}/' => $article->title,
'/{CONTENT}/' => $article->content
]);
return $view->renderHTML();
}
/
Render article list
/
private function renderArticleList($articles)
{
$html = '<div class="articles">';
foreach ($articles as $article) {
$html .= '<div class="article-item">';
$html .= '<h3><a href="?module=article&action=show&id='.$article->id.'">'.$article->title.'</a></h3>';
$html .= '<p>'.substr($article->content, 0, 150).'...</p>';
$html .= '</div>';
}
$html .= '</div>';
return $html;
}
}3. Controller for Form Handling
use Kotchasan\Database;
<?php
use Kotchasan\Controller;
use Kotchasan\Http\Request;
use Kotchasan\Input;
class ContactController extends Controller
{
/
Display contact form
/
public function form()
{
$view = View::create();
$view->setContents([
'/{TITLE}/' => 'Contact Us',
'/{FORM}/' => $this->renderContactForm()
]);
return $view->renderHTML();
}
/
Handle form submission
/
public function submit(Request $request)
{
$input = new Input($request);
// Set validation rules
$input->rules([
'name' => 'required|string|min:2',
'email' => 'required|email',
'message' => 'required|string|min:10'
]);
// Validate data
if (!$input->validate()) {
return $this->showErrors($input->getErrors());
}
// Save message
$db = Kotchasan\Database::create();
$db->insert('contacts')
->values([
'name' => $input->getString('name'),
'email' => $input->getString('email'),
'message' => $input->getString('message'),
'created_at' => date('Y-m-d H:i:s')
])
->execute();
// Show thank you page
return $this->showThankYou();
}
private function renderContactForm()
{
return '
<form method="post" action="?module=contact&action=submit">
<p>
<label>Name:</label>
<input type="text" name="name" required>
</p>
<p>
<label>Email:</label>
<input type="email" name="email" required>
</p>
<p>
<label>Message:</label>
<textarea name="message" required></textarea>
</p>
<p>
<button type="submit">Send Message</button>
</p>
</form>';
}
}4. API Controller
use Kotchasan\Database;
<?php
use Kotchasan\Controller;
use Kotchasan\Http\Request;
use Kotchasan\Http\Response;
class ApiController extends Controller
{
/
API endpoint for getting user data
/
public function getUsers(Request $request)
{
try {
// Check authentication
$this->authenticateApi($request);
// Get data
$db = Kotchasan\Database::create();
$users = $db->select(['id', 'name', 'email'])
->from('users')
->where(['active', 1])
->toArray();
// Return as JSON
return Response::json([
'success' => true,
'data' => $users
]);
} catch (\Exception $e) {
return Response::json([
'success' => false,
'error' => $e->getMessage()
], 400);
}
}
private function authenticateApi(Request $request)
{
$token = $request->getHeader('Authorization');
if (!$token || !$this->validateApiToken($token)) {
throw new \Exception('Unauthorized', 401);
}
}
}Best Practices
1. Controller Structure Organization
// Use appropriate namespaces
namespace App\Controllers;
use Kotchasan\Controller;
class UserController extends Controller
{
// Group methods by function
// Public actions
public function index() { }
public function show() { }
public function create() { }
// Protected helper methods
protected function validateUser($data) { }
protected function sendNotification($user) { }
// Private utility methods
private function formatUserData($user) { }
}2. Error Handling
class OrderController extends Controller
{
public function process(Request $request)
{
try {
// Process order
$this->validateOrder($request);
$order = $this->createOrder($request);
$this->sendConfirmation($order);
return $this->success('Order processed successfully');
} catch (ValidationException $e) {
return $this->error('Validation failed: ' . $e->getMessage(), 400);
} catch (PaymentException $e) {
return $this->error('Payment failed: ' . $e->getMessage(), 402);
} catch (\Exception $e) {
// Log error
error_log('Order processing failed: ' . $e->getMessage());
return $this->error('Internal server error', 500);
}
}
}3. Dependency Injection
class ProductController extends Controller
{
private $productService;
private $categoryService;
public function __construct(ProductService $productService, CategoryService $categoryService)
{
$this->productService = $productService;
$this->categoryService = $categoryService;
}
public function index()
{
$products = $this->productService->getAllProducts();
$categories = $this->categoryService->getAllCategories();
// Send data to view
return $this->render('products/index', compact('products', 'categories'));
}
}4. Using Middleware
class AdminController extends Controller
{
public function __construct()
{
// Check admin privileges before every action
$this->middleware('auth.admin');
}
public function dashboard()
{
// Only admins can access
return $this->render('admin/dashboard');
}
}Important Considerations
- Security: Always validate input and check access permissions
- Performance: Avoid heavy processing in Controllers, delegate to Service layer
- Separation of Concerns: Separate business logic from Controllers
- Error Handling: Handle exceptions appropriately
Related Classes
- View - For HTML rendering
- ApiController - Controller for APIs
- Request - HTTP Request handling
- Response - HTTP Response handling
- Database - Database interaction
- Input - Input validation
Additional Examples
See MVC pattern usage examples in MVC Guide and Web Development Basics