正确添加功能内的功能

时间:2011-05-31 17:55:14

标签: php function codeigniter

我正在创建一个配置文件脚本,用户可以在其中编辑他们的个人信息,兴趣和链接。

我将所有字段都放在一个表单中,但现在我想用标签分隔它们。所以我将有一个个人信息标签,兴趣标签和链接标签。在每个页面中,我将有一个表单将数据提交给相应的函数。例如,如果您正在编辑个人信息,表单将指向mysite.com/edit/personal_info

这些功能应如下所示

function edit() {

   function personal_info() {
      //data
   }   

   function interests() {
     //data
   }

   function links() {
     //data
   }

}

我不确定如何正确地将edit()函数中的数据发送到其所有子函数。

我将以下常规数据添加到我的所有函数中,但我想添加一次,所有函数都应该有。我也试图避免全局变量。

$this->db->where('user_id', $this->tank_auth->get_user_id());
$query = $this->db->get('user_profiles');
$data['row'] = $query->row();

然后在每个子函数中我都有验证规则(codeigniter)以下是personal_info函数的规则

$this->form_validation->set_rules('first_name', 'First Name', 'trim|required|xss_clean|min_length[2]|max_length[20]|alpha');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|xss_clean|min_length[2]|max_length[20]|alpha');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|xss_clean|alpha');

以及将数据添加到数据库或在验证规则失败时返回错误的语句

if ($this->form_validation->run() == FALSE) //if validation rules fail
        {           
            $this->load->view('edit_profile', $data);
        }
        else //success
        {
        $data = array (                 
                'first_name'    => $this->input->post('first_name'),
                'last_name'     => $this->input->post('last_name'),
                'gender'    => $this->input->post('gender')

            );
            $this->load->model('Profile_model');
            $this->Profile_model->profile_update($data);            
        }

如何在不重复每个子代码的情况下正确创建这些子功能?

2 个答案:

答案 0 :(得分:3)

哇,你有点失落我。你为什么在函数中使用函数?如果你正在使用CodeIgniter,那些函数应该在一个类中:

class Edit extends CI_Controller {
  function personal_info() {
    /* Do personal info stuff. */
  }

  function interests() {
    /* Do interests stuff. */
  }

  function links() {
    /* Do links stuff. */
  }

  function _common() {
    // The underscore makes the function not available to browse, but you can
    // put common code here that is called within the other functions by
    // invoking $this->_common();
  }
}

答案 1 :(得分:2)

通过编写代码的方式,看起来你正在使用codeigniter。

当你请求mysite.com/edit/personal_info时,它会请求一个名为edit的控制器和一个名为personal_info的函数,所以你不需要函数内部的函数,你只需要编辑控制器类中的函数。进一步的url段将作为参数传递给函数。

相关问题