BaseController.php
2.44 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
<?php
namespace soa\controllers;
use Yii;
use yii\web\Controller;
use soa\components\filters\AccessControl;
/**
* Site controller
*/
class BaseController extends Controller
{
public $layout = false;
//app来源,默认YOHOBUY
protected $app = 1;
//缓存句柄
protected $cache;
public function init()
{
//init
parent::init();
}
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
],
];
}
public function beforeAction($action)
{
if ($app = (int)$this->requests('app'))
{
if (!key_exists($app, Yii::$app->params['config']['app'])){
$this->renderJson(500, 'app未定义');
}
$this->app = $app;
}
$this->cache = Yii::$app->pageCache;
return parent::beforeAction($action);
}
/**
* json返回
*/
public function renderJson($code, $message, $data = '')
{
if (is_array($data)){
$retData = [
'code' => (int)$code,
'message' => $message,
'data' => $data,
'timestamp' => time(),
'md5' => md5(json_encode($data))
];
}else{
$_data = json_decode($data,true);
$retData = [
'code' => (int)$code,
'message' => $message,
'data' => is_array($_data) ? $_data : $data,
'timestamp' => time(),
'md5' => md5(strval($data))
];
}
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
Yii::$app->response->content = json_encode($retData);
Yii::$app->response->send();
Yii::$app->end();
}
public function afterAction($action, $result)
{
return parent::afterAction($action, $result);
}
/**
* 请求参数
* @return array|mixed
*/
protected function requests($name = null, $defaultValue = null)
{
$params = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
if ($name === null) {
return isset($params['parameters']) ? json_decode($params['parameters'], true) : $params;
} else {
return isset($params[$name]) ? $params[$name] : $defaultValue;
}
}
}