在Codeigniter

时间:2015-06-29 12:10:56

标签: php codeigniter

我对使用哪种技术在codeigniter中编码模型感到非常困惑。

我搜索了很多,发现了各种程序员使用的各种方法。请指导我使用codeigniter编写Model Class的最佳方法。

几个例子;

  • 有些人在方法签名

    中采用长参数
     function insert_data($name, $address, $email, $....,$...,$..)
    

    其他人只需使用以下内容并在里面写下所有邮政编码 模特..

    function insert()
    { 
    $name= $this->input->post('var1');
    $name= $this->input->post('var1');
    $name= $this->input->post('var1');
    }
    
  • 有些人为每个表创建了不同的模型,而有些只写了很少的模型..

    不同开发者之间的矛盾更多, 我在使用哪种技术来编写更高效的内容时非常困惑 和行业标准代码。

    请指导我,非常感谢

5 个答案:

答案 0 :(得分:7)

这是一个很好的问题。它可以追溯到Codeigniter的优点和缺点。因为你可以根据自己的意愿定制Codeitgniter(许多人过度使用),这些问题出现了,由开发人员来决定事物的属性。话虽如此,我将分享我如何使用模型。

根据Codeigniter的MVC标准:

  

模型代表您的数据结构。通常是你的模型   类将包含帮助您检索,插入和的函数   更新数据库中的信息。

因此,模型应该只处理与数据库的通信,或者如果不使用数据库,它应该处理从其他源(即json,文本文件等)中检索数据。

我的建议:

  • 在控制器方法中保留所有内部功能,其中包括您的所有$this->input->post()信息。获得所有post()信息后,创建必要的数组并将其传递给模型
  • 模型应该接收数组(在控制器中构建)并构建检索信息所需的数据库查询。

使用这种结构,您可以从任何控制器重用这些模型方法,保持模块化结构。

希望这有帮助。

答案 1 :(得分:3)

这可能会对你有所帮助。 (我如何在codeigniter中使用模型)

我的PHP模型文件:

<?php

class Dbmodel extends CI_Model {

function __construct() {
    parent::__construct();
    $this->db->query("SET time_zone='+05:30'");
}

function customQueryInsert($table, $array_data, $array_condition) {
    if (!empty($array_condition)) {
        $this->db->where($array_condition);
    }
    $result = $this->db->insert($table, $array_data);
    if ($result) {
        return TRUE;
    } else {
        return FALSE;
    }
}

function customQueryInsertGetId($table, $array_data, $array_condition) {
    if (!empty($array_condition)) {
        $this->db->where($array_condition);
    }
    $result = $this->db->insert($table, $array_data);
    if ($result) {
        return $this->db->insert_id();
    } else {
        return FALSE;
    }
}

function lastQuery() {
    return $this->db->last_query();
}
}

并呼吁控制器:

$this->load->model('Dbmodel', 'Dbmodel', TRUE);
$this->notification = $this->Dbmodel->customQuerySingleResult("select count(id) as ncount from notification where id='$this->id' and status='unread'", "ncount");
$this->Dbmodel->customQueryInsert("activity", array('userid' => $this->id, 'username' => $this->email, 'activity' => uri_string()), array());

这就是我在CODEIGNITER中使用MODEL的方法..在你的情况下,你可以使用下面的代码来插入你的数据,假设你是在控制器方法中写的。

$this->load->model('Dbmodel', 'Dbmodel', TRUE);
$status = $this->Dbmodel->customQueryInsert("table_name",array('column_name'=>'var1','column_two'=>'var2'));
if($status){
  //do succes stuffs
}else{
  //fail redirect...
}

现在你不需要创建带有必需参数的方法..只需调用customQueryInsert方法并将表名作为第一个参数和column_name=>column_data数组传递给第二个参数......

您可以根据需要对其进行优化..或者如果您需要进一步的帮助,请告诉我们。

答案 2 :(得分:2)

如果你转到底部的http://www.codeigniter.com/,你会看到

  

CodeIgniter鼓励MVC,但不强迫它。

  1. 这意味着您可以根据需要编写代码。
  2. 来自你的例子

    function insert_data($name, $address, $email, $....,$...,$..)function insert()更好。第一个是可重复使用的。

    假设您想使用get方法执行相同的任务。在这种情况下,您需要为get编写另一个插入函数。但是,如果从控制器传递它们,则可以重用第一个函数。

    1. $this->input->post更好的方法在控制器上使用此功能。如果你在模型的功能中使用它,这意味着该功能只能在必须有发布数据的地方工作。

答案 3 :(得分:0)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Doctor extends CI_Controller {

function __construct() {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('doctor_model');
        $this->load->library('session');
        $this->load->helper('url');
    }
    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {



        $this->form_validation->set_rules('email', 'email', 'required');
         if ($this->form_validation->run() == true) { 
           $data = array(
               'email' => $this->input->post('email'),
               'name' => $this->input->post('name'),
               'password' => $this->input->post('password')
              );

                $this->doctor_model->add('doctor',$data);
         } 
         else { 

         } 
        $this->load->view('doctor_reg');


    }


public function login()
    {
         $this->form_validation->set_rules('email', 'email', 'required');
         if ($this->form_validation->run() == true) { 
           $data = array(
               'email' => $this->input->post('email'),

                      );
            $email = $this->input->post('email');

              $logindata= $this->doctor_model->get_row('doctor','email',$email);


             if($logindata){

              $sess_array = array(
                       'id' => $logindata->id,
                       'name' => $logindata->name,
                       'email' => $logindata->email
       );

              $this->session->set_userdata('logged_in', $sess_array);
               redirect('doctor-dashboard');

             }


    }

   $this->load->view('doctor_login');


}

public function dashboard()
    {
        $session_data = $this->session->userdata('logged_in');
        $d_id=$session_data['id'];
         //$c_record['schdule']=$this->doctor_model->get_entry_by_data('schedule',false,array('d_id'=>$d_id));
         $c_record['schdule']=$this->doctor_model->get_data_by_join('schedule', 'clinik', array('schedule.d_id'=>$d_id), 'c_id', 'c_id');



        $this->load->view('dashboard',$c_record);
    }

public function add_clinick()
    {
        $session_data = $this->session->userdata('logged_in');
        $d_id=$session_data['id'];
        $this->form_validation->set_rules('c_name', 'c_name', 'required');
         if ($this->form_validation->run() == true) { 

           $data = array(
               'c_name'  => $this->input->post('c_name'),
               'address' => $this->input->post('address'),
                'd_id'   => $d_id
              );

                $add=$this->doctor_model->add('clinik',$data);

                if($add){
                    redirect('doctor-dashboard');
                }
         } 
         else { 

         }
        $this->load->view('add_clinick');
    }

public function add_schedule(){

        $session_data = $this->session->userdata('logged_in');
        $d_id=$session_data['id'];
        $session_data = $this->session->userdata('logged_in');
        $d_id=$session_data['id'];
        $this->form_validation->set_rules('clinick', 'clinick', 'required');
         if ($this->form_validation->run() == true) { 

       $data = array(
                'd_id'  => $d_id,
                'c_id'  => $this->input->post('clinick'),
                'day' => $this->input->post('day'),
                'fron_time'   => $this->input->post('f_time'),
                'to_time'   => $this->input->post('t_time')
              );
       $fron_time=$this->input->post('f_time');
       $to_time=$this->input->post('t_time');
        $c_id= $this->input->post('clinick');
           $day = $this->input->post('day');


 //$btwn='d_id='.$d_id.' day='.$day.' AND fron_time  BETWEEN '.$fron_time.' AND '.$to_time.' AND fron_time  BETWEEN '.$fron_time.' AND '.$to_time;

$wh= "d_id='".$d_id."' AND day='".$day."' AND (fron_time  BETWEEN '".$fron_time."' AND '".$to_time."' OR to_time  BETWEEN '".$fron_time."' AND '".$to_time."')";


   $ntbetwn=$this->doctor_model->get_entry_by_data('schedule',false,$wh);
   //echo $this->db->last_query();

// $c_record['schdule']=$this->doctor_model->get_entry_by_data('schedule',false,array('d_id'=>$d_id));
if($ntbetwn==''){
           $s_records = $this->doctor_model->add('schedule',$data);


               if( $s_records){

                     redirect('doctor-dashboard');
                }
}
else{
    $massage='you already schedule this time';
    $c_record['massage']=$massage;
            } 
       }


      //$c_record['clinick']= $this->doctor_model->get_row('clinik','c_id',$d_id);


      $c_record['clinick']=$this->doctor_model->get_entry_by_data('clinik',false,array('d_id'=>$d_id));

  $this->load->view('add_schedule',$c_record);


}

}

答案 4 :(得分:0)

模型示例

<?php 
class Doctor_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }


    public function add($table,$data)
    {
        return $this->db->insert($table, $data);

    }



    public function get_data($table,$primaryfield,$fieldname,$id)
    {
        $this->db->select($fieldname);
        $this->db->where($primaryfield,$id);
        $q = $this->db->get($table);
        if($q->num_rows() > 0)
        {
            return $q->result();
        }
        return array();
    }


     public function get_row($table,$primaryfield,$id)
    {
        $this->db->where($primaryfield,$id);
        $q = $this->db->get($table);
        if($q->num_rows() > 0)
        {
            return $q->row();
        }
        return false;
    }





function get_entry_by_data($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '') {

            if (!empty($select)) {
                $this->db->select($select);
            }

            if (empty($data)) {

                $id = $this->input->post('id');

                if (!$id)
                    return false;

                $data = array('id' => $id);
            }
            if (!empty($group_by)) {

                $this->db->group_by($group_by);
            }


            if (!empty($limit)) {
                $this->db->limit($limit, $offset);
            }

            if (!empty($order_by) && !empty($orderby_field)) {

                $this->db->order_by($orderby_field, $order_by);
            }

            $query = $this->db->get_where($table_name, $data);

            $res = $query->result_array();

            //echo $this->db->last_query();exit;

            if (!empty($res)) {

                if ($single)
                    return $res[0];
                else
                    return $res;
            } else
                return false;
        }


    public function get_entry_by_data_in($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '',$in_column='',$in_data=''){



            if (!empty($select)) {
                $this->db->select($select);
            }

            if (empty($data)) {

                $id = $this->input->post('id');

                if (!$id)
                    return false;

                $data = array('id' => $id);
            }
            if (!empty($group_by)) {

                $this->db->group_by($group_by);
            }


            if (!empty($limit)) {
                $this->db->limit($limit, $offset);
            }

            if (!empty($order_by) && !empty($orderby_field)) {

                $this->db->order_by($orderby_field, $order_by);
            }

            if (!empty($in_data) and !empty($in_column)) {
               $this->db->where_in($in_column,$in_data);
            }

            $query = $this->db->get_where($table_name, $data);

            $res = $query->result_array();

            //echo $this->db->last_query();exit;

            if (!empty($res)) {

                if ($single)
                    return $res[0];
                else
                    return $res;
            } else
                return false;

    }
        public function getAllRecords($table, $orderby_field = '', $orderby_val = '', $where_field = '', $where_val = '', $select = '', $limit = '', $limit_val = '') {

            if (!empty($limit)) {
                $offset = (empty($limit_val)) ? '0' : $limit_val;
                $this->db->limit($limit, $offset);
            }
            if (!empty($select)) {

                $this->db->select($select);
            }
            if ($orderby_field)
                $this->db->order_by($orderby_field, $orderby_val);

            if ($where_field)
                $this->db->where($where_field, $where_val);

            $query = $this->db->get($table);

            //return $query->num_rows;
            //echo $this->db->last_query();
            if ($query->num_rows > 0) {
                return $query->result_array();
            }
        }

        function alldata($table) {
            $query = $this->db->get($table);
            return $query->result_array();
        }

        function alldata_count($table, $where) {
            $query = $this->db->get_where($table, $where);
            return $query->num_rows();
        }

        function insert_entry($table, $data) {
            $this->db->insert($table, $data);
            return $this->db->insert_id();
        }



        function update_entry($table_name, $data, $where) {
            return $this->db->update($table_name, $data, $where);
        }

      public function get_data_by_join($table, $table2, $where, $table1_column, $table2_column, $limit = '', $order_column = '', $order_by = 'DESC', $select_columns = '', $is_single_record = false, $group_by = '', $join_by = '', $offset = '') {
            if (!empty($select_columns)) {
                $this->db->select($select_columns);
            } else {
                $this->db->select('*');
            }

            $this->db->from($table);
            $this->db->join($table2, $table . '.' . $table1_column . '=' . $table2 . '.' . $table2_column, $join_by);
            $this->db->where($where);
            if (!empty($limit)) {
                if (!empty($offset)) {
                    $this->db->limit($limit, $offset);
                } else {
                    $this->db->limit($limit);
                }
            }
            if (!empty($order_column)) {
                $this->db->order_by($order_column, $order_by);
            }

            if (!empty($group_by)) {
                $this->db->group_by($group_by);
            }

            $query = $this->db->get();
            if ($query->num_rows() > 0) {

                if ($is_single_record) {
                    $rs = $query->result_array();
                    return $rs[0];
                } else {
                    return $query->result_array();
                }
            } else {
                return false;
            }
        }

        function DeleteRecord($table_name, $where) {
            return $this->db->delete($table_name, $where);
        }

        function managerecord() {
            $count = 1;
            $where = array('channel_id' => 8,
                'field_id_12 !=' => '');
            $this->db->where($where);
            $query = $this->db->get('channel_data');
            $data = $query->result_array();
            foreach ($data as $value) {
                $id = $value['field_id_12'];
                $update = array('telephone' => $value['field_id_53'],
                    'about' => $value['field_id_54'],
                    'license' => $value['field_id_18'],
                    'broker' => $value['field_id_19'],
                    'preferred' => 'yes');
                $this->db->update('members', $update, array('member_id' => $id));
            }
            echo "done1";
        }

        public function get_content_landing_page($table = false, $field = false, $id = false, $id_name = false) {
            $this->db->select($field);
            $this->db->from($table);
            $this->db->where($id_name, $id);
            $query = $this->db->get();
            return $query->result_array();
        }

        public function get_field_landing_page($id = false,$fields=false) {
            $this->db->select($fields);
            $this->db->from('terratino_form_fields_master');
            $this->db->where('id', $id);
            $query = $this->db->get();
            return $query->result_array();
        }




}
?>