blob: 1750753c2cc32689ba22182b4d876e80bb1171de (
plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
<?php
namespace Core;
use Pimple\Container;
/**
* Router class
*
* @package core
* @author Frederic Guillot
*/
class Router
{
/**
* Controller name
*
* @access private
* @var string
*/
private $controller = '';
/**
* Action name
*
* @access private
* @var string
*/
private $action = '';
/**
* Container instance
*
* @access private
* @var Pimple\Container
*/
private $container;
/**
* Constructor
*
* @access public
* @param Pimple\Container $container Container instance
* @param string $controller Controller name
* @param string $action Action name
*/
public function __construct(Container $container, $controller = '', $action = '')
{
$this->container = $container;
$this->controller = empty($_GET['controller']) ? $controller : $_GET['controller'];
$this->action = empty($_GET['action']) ? $action : $_GET['action'];
}
/**
* Check controller and action parameter
*
* @access public
* @param string $value Controller or action name
* @param string $default_value Default value if validation fail
* @return string
*/
public function sanitize($value, $default_value)
{
return ! ctype_alpha($value) || empty($value) ? $default_value : strtolower($value);
}
/**
* Load a controller and execute the action
*
* @access public
* @param string $filename Controller filename
* @param string $class Class name
* @param string $method Method name
* @return bool
*/
public function load($filename, $class, $method)
{
if (file_exists($filename)) {
require $filename;
if (! method_exists($class, $method)) {
return false;
}
$instance = new $class($this->container);
$instance->request = new Request;
$instance->response = new Response;
$instance->session = new Session;
$instance->template = new Template;
$instance->beforeAction($this->controller, $this->action);
$instance->$method();
return true;
}
return false;
}
/**
* Find a route
*
* @access public
*/
public function execute()
{
$this->controller = $this->sanitize($this->controller, 'app');
$this->action = $this->sanitize($this->action, 'index');
$filename = __DIR__.'/../Controller/'.ucfirst($this->controller).'.php';
if (! $this->load($filename, '\Controller\\'.$this->controller, $this->action)) {
die('Page not found!');
}
}
}
|