【发布时间】:2013-06-17 01:29:22
【问题描述】:
背景
使用Codeigniter 与form_helper 和form_validation 进行一些表单处理。 controller 中的表单已成功验证。
现在我们需要使用model 类将这些数据放入数据库中。
假设
假设我们的表单有多个输入元素(例如 >20)。
问题
以下哪个代码 sn-ps 会更高效? 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() 和post() 函数(请参见下文),显然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);
}
【问题讨论】:
标签: php forms codeigniter validation codeigniter-2