Yii2 components api/controller

When we wrote API, those controllers need to implement the following feature:

1. return JSON format data

2. sometimes support JSONP format data also.

3. support stupid low version IE

If we set format with Yii2, the low version IE will download the response content as a file.

Yii::$app->response->format = Response::FORMAT_JSON

  

So I wrote a component for it, any API controller just need to extend it.

 1 namespace api\components;
 2 
 3 use Yii;
 4 use yii\web\Response;
 5 
 6 class Controller extends \yii\web\Controller
 7 {
 8     protected $isLowIE;
 9     protected $callback;
10 
11     public function beforeAction($action)
12     {
13         $this->layout = false;
14         $this->callback = Yii::$app->request->get('callback', false);
15 
16         $this->isLowIE = (boolean)Yii::$app->request->get('ie', false);
17 
18         if (!$this->isLowIE && !$this->callback) {
19             Yii::$app->response->format = Response::FORMAT_JSON;
20         }
21 
22         return parent::beforeAction($action);
23     }
24 
25     /**
26      * @param \yii\base\Action $action
27      * @param mixed $result
28      * @return mixed
29      */
30     public function afterAction($action, $result)
31     {
32         $result = parent::afterAction($action, $result);
33         // your custom code here
34         if ($this->isLowIE || $this->callback) {
35             $result = json_encode($result);
36 
37             if ($this->callback) {
38                 $result = $this->callback .'('. $result .')';
39             }
40         }
41         return $result;
42     }
43 }

 

posted on 2017-04-18 17:35  技术员  阅读(496)  评论(0编辑  收藏  举报

导航