背景と
を使用Codeigniter
してフォーム処理を行います。でフォームが正常に検証されました。form_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()
および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);
}