- A+
我们先来看下 tp5 控制器来的 构造方法:
/** * 构造方法 * @param Request $request Request对象 * @access public */ public function __construct(Request $request = null) { if (is_null($request)) { $request = Request::instance(); } $this->view = View::instance(Config::get('template'), Config::get('view_replace_str')); $this->request = $request; // 控制器初始化 $this->_initialize(); // 前置操作方法 ...... }
可以看到,在控制器中已经实例化了 Request类。
那么,在控制器中,如何快速获取参数值呢?
$this->request->param("name");//接受参数名
详细可以参照 thinkphp5 的官方文档 https://www.kancloud.cn/manual/thinkphp5/118042
对于表单内容参数很多的情况下,我们接受参数可以使用 $this->request->post() 或者 单个接收,但这样代码十分不优雅,我们可以在 common/controller/Base.php下 加入如下代码接收参数:
/** * 从网页接收提交数据 * @param array $params 需要接收的数据[0=>'user_name']/['username'=>'user_name/s'] * @param string $method 获取方式get/post/input * @return array */ protected function buildParams($params = [], $method = 'param') { $result_data = []; if (empty($params)) { return $this->request->$method(); } else if (is_array($params) && !empty($params)) { foreach ($params as $index => $item) { if(is_array($item) && isset($item['callback']) && is_callable($item['callback'])) { $result_data[$index] = call_user_func($item['callback'],$index); } else if (is_numeric($index)) { $result_data[$item] = $this->protectStr($this->request->$method($item)); } else { $result_data[$index] = $this->protectStr(($this->request->$method($item))); } } } else if (is_string($params)) { $result_data = $this->protectStr($this->request->$method($params)); } return $result_data; }
在控制器中调用如下:
$params = ['user_name'=>'username','password','check_code','login_time' => ['callback'=>function(){ return time(); }]]; $login_data = $this -> buildParams($params,'post');
此外,如果在seller 模块下有固定的参数(如 seller_id),我们可以在 seller/controller/Base.php 中重写此方法:
public function buildParams($params = array(), $method = 'param') { $params_data = parent::buildParams($params, $method); if (is_array($params_data) && key_exists('seller_id', $params_data) && empty($params_data['seller_id'])) { $params_data['seller_id'] = $this->seller_id; } return $params_data; }