Much cleaner and basic MY_Model for CodeIgniter

This post was originally published in 2010
The tips and techniques explained may be outdated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
 class MY_Model extends Model {
   
    /**
     * The table name of this db table
     * @var String
     */

    private $_table;
   
    public function __construct() {
        parent::Model();
    }
   
    public function setTable($table) {
        $this->_table = $table;
    }
   
    /**
     * This method inserts some array of data into the db
     * @param Array $data
     * @return Int Insert ID
     */

    public function add($data) {
        if(is_array($data)) {
            $this->db->insert($this->table, $data);
            return $this->db->insert_id();
        } else {
            $this->log('error', 'Got non-array param.', __METHOD__);
            return FALSE;
        }
    }
   

    /**
     * Updates row with the data array given
     * @param $data
     * @param $where Mixed Array
     */

    public function update($data, $where) {
        if(!is_array($data)) {
            $this->log('error', 'Supposed to get an array!', __METHOD__);
            return FALSE;
        } else {
            /*
            // write the old&new data to history
            foreach($RowData as $fieldName=>$fieldValue) {
                $this->history->write($this->table, $RowID, $fieldName, $fieldValue);
            }
            */

            foreach ($where as $field => $value) {
                $this->db->where($field, $value);
            }
           
            $this->db->update($this->_table, $data);
        }
    }
   
   
    /**
     * This method logically deletes a row.
     * @param Integer $rowID
     * @return Boolean
     */

    public function delete($rowID) {
        if(is_numeric($rowID)) {
            $this->updateField('IsDeleted', 1, $rowID);
            return TRUE;
        } else {
            return FALSE;
        }
    }
   
   
    /**
     * Logs an error
     * @param String $level
     * @param String $msg
     */

    final protected function log($level, $msg, $method=__METHOD__) {
        log_message($level, $method.' :: '.$msg.' [In: '.__FILE__.' Line: '.__LINE__.']');
    }
   
    public function __call($name, $arguments) {
        $args = implode(',',$arguments);
        $this->log('error', $name.'('.$args.') Not exists.', __METHOD__);
        return FALSE;
    }
 }

Related Posts

  • No Related Posts
  • Babrah

    this is good

    • http://udiudi.com Udi Mosayev

      Thank you :)

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera