Controllers
Creating Controllers to handle requests
The sirJuni Framework is MVC architecture based, so to create controllers for handling requests we have complete freedom of naming the handlers as we would later bind the requested url to a handler which then uses the VIEW
class found at sirJuni\Framework\View\VIEW;
to render pages.
Every single controller method should take a single argument $request
which contains the instance of current request.
An example of a controller would be
<?php
require_once __DIR__ . "\\..\\vendor\\autoload.php";
use sirJuni\Framework\View\VIEW;
class HomeController {
public function index($request) {
VIEW::init('index.html');
}
}
?>
It is a simple Home Page controller, which on receiving a request, just renders the index.html
page.
Rendering with Context
To render html pages with access to data its called rendering with context. The context here are all the data that is made available to the page.
To give context to an html page, we have to create an array lets say $context = []
and then load all the data needed in the html file into this context array. After that we just give this $context array to the VIEW::init('index.html', $context)
which extracts this array in the scope of the html
page. This will give us access to this data.
Implemented in code it looks like:
class HomeController {
public function show($request) {
$context = [];
// grab all the post data from the request
foreach($request->formKeys() as $key) {
$context[$key] = $request->formData($key);
}
// grab data from db
$db = new DB(); // extends Database class
$data = $db->getUsers();
$context = array_merge($context, $data); // $data is an associative array
// give it to init
VIEW::init('index.html', $context);
}
}
Last updated