What is the best way to write Model code in Codeig

2019-04-09 09:44发布

问题:

I am very much confused regarding which technique to use to code Model in codeigniter.

I searched a lot and found various methods used by various coders. Kindly guide me the best way to write Model Class using codeigniter.

Few examples;

  • Some take long parameters in Method signature

     function insert_data($name, $address, $email, $....,$...,$..)
    

    While others just use the following and write all post code inside Model..

    function insert()
    { 
    $name= $this->input->post('var1');
    $name= $this->input->post('var1');
    $name= $this->input->post('var1');
    }
    
  • Some create different Model for each Table, while some write very few Models..

    And many more contradictions between different developers, I am so much confused in which technique to use to write more efficient and industry standard code.

    Kindly guide me Thanks a lot

回答1:

This is a good question. It goes back on the pros and cons of Codeigniter. Being that you can customize Codeitgniter as much as you wish (which a lot of people overdo), issues like these come up, where its up to the developer to decide where things belong. With that being said, I will share how I use models.

According to Codeigniter's MVC standards:

The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.

Therefore a model should only handle the communication with your database, or if you don't use databases, it should handle the retrieval of data from other sources (i.e. json, text files, etc...).

What I recommend:

  • Keep all your internal functionalities in your controller method, this includes all your $this->input->post() information. Once you have all your post() information, create the necessary array and pass it to the model
  • The model, should receive the array (which you constructed in your controller) and build the database queries needed to retrieve the information.

With this structure, you may reuse these model methods from any controllers, keeping a modular structure.

Hope this helps.



回答2:

this might help you. (how i use model in codeigniter)

MY MODEL PHP FILE:

<?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();
}
}

AND CALLING IN CONTROLLER:

$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());

this is how i use MODEL in CODEIGNITER.. in your case you can use below code to insert your data, assuming you are writing it inside a controller method.

$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...
}

now you dont need to create methods with required parameters.. just call customQueryInsert method and pass table name as first parameter and array of column_name=>column_data to second parameter...

you can optimize it according to your need.. or if you want further help please let me know..



回答3:

If you go to http://www.codeigniter.com/ at the bottom you will see

CodeIgniter encourages MVC, but does not force it on you.

  1. It means you can write your code as you want.

From your example

function insert_data($name, $address, $email, $....,$...,$..) is better way than function insert(). 1st one is reusable.

Suppose you want do same task using get method.In that case you need to write another insert function for get.but 1st one can be reused if you pass them from your controller.

  1. $this->input->post better way to use this function at controller.If you use it at model's function that means that function will only work where there must be post data.


回答4:

<?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);


}

}


回答5:

model example

<?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();
        }




}
?>