BaseController.php 2.44 KB
<?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;
        }
    }
}