BaseController.php
3.07 KB
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
116
117
118
119
120
121
<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use yii\helpers\ArrayHelper;
use backend\components\filters\AccessControl;
/**
* Site controller
*/
class BaseController extends Controller
{
public $layout = 'template';
protected $_actionParams = [];
protected $_refer;
public function init()
{
if (Yii::$app->user->isGuest){
$this->redirect('/site/login');
Yii::$app->end();
}
parent::init();
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [];
return ArrayHelper::merge(parent::behaviors(), [
[
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
],
],
]);
}
public function beforeAction($action) {
Yii::setAlias('@web', Yii::getAlias('@admin'));
Yii::$app->setHomeUrl(Yii::getAlias('@web'));
Yii::$app->getRequest()->setBaseUrl(Yii::getAlias('@web'));
Yii::$app->getRequest()->setScriptUrl(Yii::getAlias('@web'));
Yii::$app->language = 'zh-CN';
$this->_refer = \common\lib\Referer::get();
$view = $this->getView();
$view->params['main_title'] = @Yii::$app->params['menu'][Yii::$app->controller->id][0] ? : '';
$view->params['sub_title'] = @Yii::$app->params['menu'][Yii::$app->controller->id][1][Yii::$app->controller->action->id][0] ? : '';
return parent::beforeAction($action);
}
/**
* 单个设置视图变量
* @param type $name
* @param type $value
* @return \backend\controllers\BaseController
*/
protected function setParam($name,$value) {
$this->_actionParams[$name] = $value;
return $this;
}
/**
* 批量设置视图变量
* @param array $params
* @return \backend\controllers\BaseController
*/
protected function setParams(array $params) {
$this->_actionParams = array_merge($this->_actionParams, $params);
return $this;
}
/**
* json返回
*/
public function renderJson($code,$message,$data = ''){
header('Content-type: application/json');
$retData = [
'code' => (int)$code,
'message' => $message,
'data' => $data,
'md5' => $data ? md5(json_encode($data)):''
];
echo json_encode($retData);
Yii::$app->end();
}
/**
* 视图输出方法重载
* @param type $view
* @param type $params
* @return type
*/
public function render($view, $params = array()) {
$params = array_merge($this->_actionParams, [
'_refer'=>$this->_refer
], $params);
return parent::render($view, $params);
}
public function afterAction($action, $result) {
return parent::afterAction($action, $result);
}
}