背景
使用Codeigniter
withform_helper
和form_validation
做一些表单处理。表单已在controller
.
现在我们需要使用model
该类将这些数据放入数据库中。
假设
让我们假设我们的表单有几个输入元素(例如>20)。
问题
以下哪个代码片段会更有效?Both snippets are obviously inside the controller method to which the form submits data.
代码片段 1
if ($this->form_validation->run())
{
// validation successful, now collect the values in a variable to pass it to the model.
$form_data['field1'] = $this->form_validation->set_value('field1');
$form_data['field2'] = $this->form_validation->set_value('field2');
// AND SO ON
$form_data['fieldN'] = $this->form_validation->set_value('fieldN');
// Now put this data into database.
$this->corresponding_model->write_to_db($form_data);
}
代码片段 2
if ($this->form_validation->run())
{
// validation successful, now collect the values in a variable to pass it to the model.
$form_data['field1'] = $this->input->post('field1');
$form_data['field2'] = $this->input->post('field2');
// AND SO ON
$form_data['fieldN'] = $this->input->post('fieldN');
// Now put this data into database.
$this->corresponding_model->write_to_db($form_data);
}
所以本质上我要问的是:获取某些任意表单元素的发布数据更好吗?$this->input->post
还是$this->form_validation->set_value()
?
PS:如果我们查看代码中的set_value()
andpost()
函数(请参见下文),显然set_value()
会更快,因为post()
循环遍历整个$_POST
. 所以从某种意义上说,它也是关于什么是最佳实践?
Form_validation.php, set_value() 方法
public function set_value($field = '', $default = '')
{
if ( ! isset($this->_field_data[$field]))
{
return $default;
}
// If the data is an array output them one at a time.
// E.g: form_input('name[]', set_value('name[]');
if (is_array($this->_field_data[$field]['postdata']))
{
return array_shift($this->_field_data[$field]['postdata']);
}
return $this->_field_data[$field]['postdata'];
}
Input.php, post() 方法
function post($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
}
return $post;
}
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}