Controller.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. /* *****************************************************************
  3. * @Author: wushuiyong
  4. * @Created Time : 一 7/20 15:52:01 2015
  5. *
  6. * @File Name: components/Controller.php
  7. * @Description:
  8. * *****************************************************************/
  9. namespace app\components;
  10. use yii;
  11. class Controller extends yii\web\Controller {
  12. /**
  13. * json渲染. PS:调用此方法之前若有输出将会出错
  14. *
  15. * @param mixed $data
  16. * @param int $code 0成功 非0错误
  17. * @param string $msg 错误信息
  18. * @param int $option json_encode options
  19. */
  20. public static function renderJson($data, $code = 0, $msg = '', $option = 0) {
  21. Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
  22. $ret = [
  23. 'code' => (int)$code,
  24. 'msg' => $msg,
  25. 'data' => $data,
  26. ];
  27. Yii::$app->response->data = $ret;
  28. Yii::$app->end();
  29. }
  30. /**
  31. * 获取参数(post/get)的值, 优先级:post > get > default
  32. *
  33. * @param string $name 参数名字
  34. * @param mixed $default 默认值
  35. * @return mixed
  36. */
  37. public static function getParam($name, $default = null) {
  38. $post = Yii::$app->request->post($name);
  39. $get = Yii::$app->request->get($name);
  40. return isset($_POST[$name]) ? $post : (isset($_GET[$name]) ? $get : $default);
  41. }
  42. }