-
Notifications
You must be signed in to change notification settings - Fork 1
/
SlimC.php
81 lines (61 loc) · 2.18 KB
/
SlimC.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
<?php
namespace Slim;
class SlimC extends Slim
{
public function controller($baseRoute, $controllerName, $routes)
{
$controllerClass = $this->config('controller.namespace') . '\\' . $controllerName;
foreach ($routes as $subRoute => $controllerFunction) {
list($methods, $subRoute) = explode(' ', $subRoute);
if ($subRoute == '/') { $subRoute = ''; }
$finalRoute = $baseRoute . $subRoute;
$methodArray = explode(',', $methods);
$route = new Route($finalRoute, function() use(
$baseRoute,
$controllerClass,
$controllerFunction
) {
$controllerInstance = $controllerClass::getInstance($baseRoute);
$args = func_get_args();
call_user_func_array(array($controllerInstance, $controllerFunction), $args );
});
$this->router->map($route);
call_user_func_array(array($route, 'via'), $methodArray);
$route->name($controllerName . '.' . $controllerFunction);
}
}
}
abstract class Controller
{
private static $instance;
protected static $baseRoute;
protected $app, $basePath;
final private function __construct($baseRoute)
{
self::$baseRoute = $baseRoute;
$this->app = Slim::getInstance();
if (empty($this->basePath)) {
$this->basePath = $baseRoute;
}
$this->init();
}
abstract protected function init();
public final static function getInstance($baseRoute)
{
if (!isset(self::$instance)) {
$class = get_called_class();
self::$instance = new $class($baseRoute);
}
if (self::$instance instanceof $class) {
return self::$instance;
} else {
throw new Exception('Only one controller may be active at the time.');
}
}
protected function render($template, $extraVars = array())
{
$vars = array_merge($this->vars, $extraVars);
$templatePath = substr($this->basePath, 1) . '/' . $template;
$this->app->render($templatePath, $vars);
}
}