-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.php
90 lines (78 loc) · 2.22 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
// file: index.php
/**
* Default controller if any controller is passed in the URL
*/
define("DEFAULT_CONTROLLER", "posts");
/**
* Default action if any action is passed in the URL
*/
define("DEFAULT_ACTION", "index");
/**
* Main router (single entry-point for all requests)
* of the MVC implementation.
*
* This router will create an instance of the corresponding
* controller, based on the "controller" parameter and call
* the corresponding method, based on the "action" parameter.
*
* The rest of GET or POST parameters should be handled by
* the controller itself.
*
* Parameters:
* <ul>
* <li>controller: The controller name (via HTTP GET)
* <li>action: The name inside the controller (via HTTP GET)
* </ul>
*
* @return void
*
* @author lipido <[email protected]>
*/
function run() {
// invoke action!
try {
if (!isset($_GET["controller"])) {
$_GET["controller"] = DEFAULT_CONTROLLER;
}
if (!isset($_GET["action"])) {
$_GET["action"] = DEFAULT_ACTION;
}
// Here is where the "magic" occurs.
// URLs like: index.php?controller=posts&action=add
// will provoke a call to: new PostsController()->add()
// Instantiate the corresponding controller
$controller = loadController($_GET["controller"]);
// Call the corresponding action
$actionName = $_GET["action"];
$controller->$actionName();
} catch(Exception $ex) {
//uniform treatment of exceptions
die("An exception occured!!!!!".$ex->getMessage());
}
}
/**
* Load the required controller file and create the controller instance
*
* @param string $controllerName The controller name found in the URL
* @return Object A Controller instance
*/
function loadController($controllerName) {
$controllerClassName = getControllerClassName($controllerName);
require_once(__DIR__."/controller/".$controllerClassName.".php");
return new $controllerClassName();
}
/**
* Obtain the class name for a controller name in the URL
*
* For example $controllerName = "users" will return "UsersController"
*
* @param $controllerName The name of the controller found in the URL
* @return string The controller class name
*/
function getControllerClassName($controllerName) {
return strToUpper(substr($controllerName, 0, 1)).substr($controllerName, 1)."Controller";
}
//run!
run();
?>