The Controller

In KISSMVC, the job of the controller is to parse the HTTP Request and routes the program control to the appropriate function.

The KISSMVC URL looks like this: http://example.com/controller/action/param1/param2

With the above URL, KISSMVC includes a file "controller.php" and calls the function "action(param1,param2)"

Note: mod_rewrite is required.

Here are the controller functions:

<?php
function requestRouter() {
  
$controller=defined('DEFAULT_ROUTE')?DEFAULT_ROUTE:'main';
  
$action=defined('DEFAULT_ACTION')?DEFAULT_ACTION:'index';
  
$params=array();
  if (
function_exists('requestParserCustom'))
    
requestParserCustom($controller,$action,$params);
  else
    
requestParser($controller,$action,$params);
  if (
function_exists('controllerRouterCustom'))
    require(
controllerRouterCustom($controller));
  else
    require(
controllerRouter($controller));
  if (!
function_exists($action))
    die(
viewFetch('404.php'));
  
call_user_func_array($action,$params);
}

//This function parses the HTTP request to get the controller, action and parameter parts.
function requestParser(&$controller,&$action,&$params) {
  
$requri=preg_replace('#^'.addslashes(WEB_FOLDER).'#'''$_SERVER['REQUEST_URI']);
  
preg_match('#^([^/]+)\/{0,1}$#'$requri$matches);
  if (
count($matches)==2)
    
$controller=$matches[1];
  else {
    
preg_match('#^([^/]+)/([^/]+)/?(.*)$#'$requri$matches);
    if (isset(
$matches[1]))
      
$controller=$matches[1];
    if (isset(
$matches[2]))
      
$action=$matches[2];
    if (isset(
$matches[3]) && $matches[3])
      
$params=explode('/',$matches[3]);
  }
  if (!
preg_match('#^[A-Za-z0-9_-]+$#',$action) || function_exists($action))
    die(
viewFetch('404.php'));
}

//This function maps the controller name to the file location of the .php file to include
function controllerRouter($controller) {
  
$controllerfile=APP_PATH.'controllers/'.$controller.'.php';
  if (!
preg_match('#^[A-Za-z0-9_-]+$#',$controller) || !file_exists($controllerfile))
    die(
viewFetch('404.php'));
  return 
$controllerfile;
}
?>