/
controller.php
89 lines (74 loc) · 1.93 KB
/
controller.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
<?php
class core_controller {
const DIR = 'controller';
const DEFAULT_CONTROLLER = 'index';
const DEFAULT_ACTION = 'index';
const ACTION_SUFFIX = 'Action';
protected $_actionMethod;
/** @var core_request */
protected $_request;
/** @var core_layout */
protected $_layout;
/**
* @param $request
* @return $this
*/
public function setRequest( $request ){
$this->_request = $request;
return $this;
}
/**
* @return core_request
*/
public function getRequest(){
return $this->_request;
}
/**
* @return core_layout
*/
public function initLayout(){
$this->_layout = new core_layout();
return $this->getLayout();
}
/**
* @return core_layout
*/
public function getLayout(){
if( !$this->_layout){
$this->initLayout();
}
return $this->_layout;
}
public function renderLayout(){
$this->getLayout()->render();
}
/**
* @return $this
* @throws core_exception
*/
public function dispatchAction( ){
$action = $this->getRequest()->getActionName();
$actionMethod = $action.self::ACTION_SUFFIX;
if(!method_exists($this,$actionMethod)){
throw new core_exception_controller("Controller action {$actionMethod} not found");
}
$this->_actionMethod = $actionMethod;
$this->_predispatchAction();
$actionMethod = $this->_actionMethod;
$this->$actionMethod();
return $this;
}
protected function _predispatchAction(){
return $this;
}
protected function _redirect($url){
header("Location: {$url}");
die();
}
static function okJson($data=null){
return json_encode(array('ok'=>true,'data'=>$data));
}
static function errJson($err){
return json_encode(array('ok'=>false,'err'=>$err));
}
}