Welcome Guest, Not a member yet? Register   Sign In
A Base Model Template
#1

[eluser]freshface[/eluser]
I found a base_model example once that you use to extend your own ones
But my bookmark is corrupted and after searching I dont find it.

Any idea if you know where it is on this forum?

Regards
#2

[eluser]Johan André[/eluser]
I use this... Suit my needs at the moment.
Don't remember where I found it though... And I think I might have been doing some mods too...

Code:
<?php
class MY_Model extends Model
{
     var $use_dbconfig = 'default';
    var $id = null;
    var $data = array();
    var $table;
    var $primary_key = 'id';
    var $fields = array();
    var $__insert_id = null;
    var $__num_rows = null;
    var $__affected_rows = null;    
    var $return_array = TRUE;
    var $debug = FALSE;
    var $queries = array();
    var $_parent_name = '';

    function MY_Model()
    {
        parent::Model();
        
        $this->_assign_libraries( (method_exists($this, '__get') OR method_exists($this, '__set')) ? FALSE : TRUE );
        
        // We don't want to assign the model object to itself when using the
        // assign_libraries function below so we'll grab the name of the model parent
        $this->_parent_name = ucfirst(get_class($this));
        
        log_message('debug', "Model Class Initialized");
    }
        
    /**
     * Assign Libraries
     *
     * Creates local references to all currently instantiated objects
     * so that any syntax that can be legally used in a controller
     * can be used within models.  
     *
     * @access private
     */    
    function _assign_libraries($use_reference = TRUE)
    {
        $CI =& get_instance();                
        foreach (array_keys(get_object_vars($CI)) as $key)
        {
            if ( ! isset($this->$key) AND $key != $this->_parent_name)
            {            
                // In some cases using references can cause
                // problems so we'll conditionally use them
                if ($use_reference == TRUE)
                {
                    // Needed to prevent reference errors with some configurations
                    $this->$key = '';
                    $this->$key =& $CI->$key;
                }
                else
                {
                    $this->$key = $CI->$key;
                }
            }
        }        
    }
    
    /**
     * Load the associated database table.
     *
     * @author md emran hasan <[email protected]>
     * @access public
     */    
    
    function load_table($table, $config = 'default')
    {
        if ($this->debug) log_message('debug', "Loading model table: $table");
        
        $this->table = $table;
        $this->use_dbconfig = $config;
        
        $this->load->database($config);
        $this->fields = $this->db->list_fields($table);
        
        if ($this->debug)
        {
            log_message('debug', "Successfull Loaded model table: $table");
        }
    }            
    
    /**
     * Returns a resultset array with specified fields from database matching given conditions.
     *
     * @author md emran hasan <[email protected]>
     * @return query result either in array or in object based on model config
     * @access public
     */    

    function find_all($conditions = NULL, $fields = '*', $order = NULL, $start = 0, $limit = NULL)
    {
        if ($conditions != NULL)
        {
            $this->db->where($conditions);
        }

        if ($fields != NULL)
        {
            $this->db->select($fields, FALSE);
        }
        
        if ($order != NULL)
        {
            $this->db->orderby($order);
        }
        
        if ($limit != NULL)
        {
            $this->db->limit($limit, $start);
        }
        
        $query = $this->db->get($this->table);
        $this->__num_rows = $query->num_rows();
        
        if ($this->debug)
        {
            $this->queries[] = $this->db->last_query();
        }
        
        return ($this->return_array) ? $query->result_array() : $query->result();
    }
    
    /**
     * Return a single row as a resultset array with specified fields from database matching given conditions.
     *
     * @author md emran hasan <[email protected]>
     * @return single row either in array or in object based on model config
     * @access public
     */    

    function find($conditions = NULL, $fields = '*', $order = 'id ASC')
    {
        $data = $this->find_all($conditions, $fields, $order, 0, 1);
        
        if ($data)
        {
            return $data[0];
        }
        else
        {
            return false;
        }
    }
    
    /**
     * Returns contents of a field in a query matching given conditions.
     *
     * @author md emran hasan <[email protected]>
     * @return string the value of the field specified of the first row
     * @access public
     */    

    function field($conditions = null, $name, $fields = '*', $order = 'id ASC')
    {
        $data = $this->find_all($conditions, $fields, $order, 0, 1);
        
        if ($data)
        {    
            $row = $data[0];
            
            if (isset($row[$name]))
            {
                return $row[$name];
            }
            else
            {
                return false;
            }    
        }
        else
        {    
            return false;    
        }
        
    }
    
    /**
     * Returns number of rows matching given SQL condition.
     *
     * @author md emran hasan <[email protected]>
     * @return integer the number of records returned by the condition
     * @access public
     */    

    function find_count($conditions = null)
    {
        $data = $this->find_all($conditions, 'COUNT(*) AS count', null, 0, 1);
        
        if ($data)
        {
            return $data[0]['count'];
        }
        else
        {
            return false;
        }
    }
#3

[eluser]Johan André[/eluser]
...continued:

Code:
/**
     * Returns a key value pair array from database matching given conditions.
     *
     * Example use: generateList(null, '', 0. 10, 'id', 'username');
     * Returns: array('10' => 'emran', '11' => 'hasan')
     *
     * @author md emran hasan <[email protected]>
     * @return array a list of key val ue pairs given criteria
     * @access public
     */    

    function generate_list($conditions = null, $order = 'id ASC', $start = 0, $limit = NULL, $key = null, $value = null, $first_key = '-1', $first_value = 'Inget valt')
    {
        $data = $this->find_all($conditions, "$key, $value", $order, $start, $limit);
    
        if ($data)
        {
            
            if($first_key != NULL)
            {
                $keys[] = $first_key;
                $vals[] = $first_value;
            }
            
            foreach ($data as $row)
            {
                $keys[] = ($this->return_array) ? $row[$key] : $row->$key;
                $vals[] = ($this->return_array) ? $row[$value] : $row->$value;
            }
                
            if (!empty($keys) && !empty($vals))
            {
                $return = array_combine($keys, $vals);
                return $return;
            }            
        }
        else
        {
            return false;
        }
    }
    
    /**
     * Returns an array of the values of a specific column from database matching given conditions.
     *
     * Example use: generateSingleArray(null, 'name');
     *
     * @author md emran hasan <[email protected]>
     * @return array a list of key value pairs given criteria
     * @access public
     */    

    function generate_single_array($conditions = null, $field = null, $order = 'id ASC', $start = 0, $limit = NULL)
    {
        $data = $this->find_all($conditions, "$field", $order, $start, $limit);
    
        if ($data)
        {    
            foreach ($data as $row)
            {
                $arr[] = ($this->return_array) ? $row[$field] : $row->$field;
            }
            
            return $arr;
        }
        else
        {
            return false;
        }
    }

    /**
     * Initializes the model for writing a new record.
     *
     * @author md emran hasan <[email protected]>
     * @return boolean True
     * @access public
     */    

    function create()
    {
        $this->id = false;
        unset ($this->data);
        
        $this->data = array();
        return true;
    }    

    /**
     * Returns a list of fields from the database and saves in the model
     *
     * @author md emran hasan <[email protected]>
     * @return array Array of database fields
     * @access public
     */    

    function read($id = null, $fields = null)
    {
        if ($id != null)
        {
            $this->id = $id;
        }

        $id = $this->id;

        if ($this->id !== null && $this->id !== false)
        {
            $this->data = $this->find($this->primary_key . ' = ' . $id, $fields);
            return $this->data;    
        }
        else
        {
            return false;    
        }
    }

    /**
     * Inserts a new record in the database.
     *
     * @author md emran hasan <[email protected]>
     * @return boolean success
     * @access public
     */    

    function insert($data = null)
    {
        if ($data == null)
        {
            return FALSE;
        }
        
        $this->data = $data;
        $this->data['create_date'] = date("Y-m-d H:i:s");
        
        foreach ($this->data as $key => $value)
        {
            if (array_search($key, $this->fields) === FALSE)
            {
                unset($this->data[$key]);
            }
        }

        $this->db->insert($this->table, $this->data);
        
        if ($this->debug)
        {
            $this->queries[] = $this->db->last_query();
        }
        
        $this->__insert_id = $this->db->insert_id();
        return $this->__insert_id;
    }    
    
    /**
     * Saves model data to the database.
     *
     * @author md emran hasan <[email protected]>
     * @return boolean success
     * @access public
     */    

    function save($data = null, $id = null, $xss = TRUE)
    {
        if ($data)
        {
            $this->data = $data;
        }
            
        foreach ($this->data as $key => $value)
        {
            
            if (array_search($key, $this->fields) === FALSE)
            {
                unset($this->data[$key]);
            }
        }
        
        if($xss)
        {
            $this->data = $this->input->xss_clean($this->data);    
        }
        
        if ($id != null)
        {
            $this->id = $id;
        }

        $id = $this->id;

        if ($this->id !== null && $this->id !== false)
        {    
            $this->db->where($this->primary_key, $id);
            $this->db->update($this->table, $this->data);
            
            if ($this->debug)
            {
                $this->queries[] = $this->db->last_query();
            }
            
            $this->__affected_rows = $this->db->affected_rows();
            return $this->id;            
        }
        else
        {
            $this->db->insert($this->table, $this->data);
            
            if ($this->debug)
            {
                $this->queries[] = $this->db->last_query();
            }
            
            $this->__insert_id = $this->db->insert_id();
            return $this->__insert_id;
        }
    }
#4

[eluser]Johan André[/eluser]
...continued...

Code:
/**
     * Removes record for given id. If no id is given, the current id is used. Returns true on success.
     *
     * @author md emran hasan <[email protected]>
     * @return boolean True on success
     * @access public
     */    

    function remove($id = null)
    {
        if ($id != null)
        {
            $this->id = $id;
        }

        $id = $this->id;

        if ($this->id !== null && $this->id !== false)
        {    
            if ($this->db->delete($this->table, array($this->primary_key => $id)))
            {
                $this->id = null;
                $this->data = array();
                
                if ($this->debug)
                {
                    $this->queries[] = $this->db->last_query();
                }
                
                return true;    
            }
            else
            {    
                return false;    
            }
        }
        else
        {
            return false;    
        }
    }    
    
    /**
     * Returns a resultset for given SQL statement. Generic SQL queries should be made with this method.
     *
     * @author md emran hasan <[email protected]>
     * @return array Resultset
     * @access public
     */    

    function query($sql)
    {
        $ret = $this->db->query($sql);
        
        if ($this->debug)
        {
            $this->queries[] = $this->db->last_query();
        }
        
        return $ret;
    }
    
    /**
     * Returns the last query that was run (the query string, not the result).
     *
     * @author md emran hasan <[email protected]>
     * @return string SQL statement
     * @access public
     */    

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

    /**
     * Returns the list of all queries peformed (if debug is TRUE)
     *
     * @author md emran hasan <[email protected]>
     * @return array list of SQL statements
     * @access public
     */    

    function debug_queries()
    {
        $queries = array_reverse($this->queries);
        return $queries;
    }        

    /**
     * This function simplifies the process of writing database inserts. It returns a correctly formatted SQL insert string.
     *
     * @author md emran hasan <[email protected]>
     * @return string SQL statement
     * @access public
     */    

    function insert_string($data)
    {
        return $this->db->insert_string($this->table, $data);
    }
    
    /**
     * Returns the current record's ID.
     *
     * @author md emran hasan <[email protected]>
     * @return integer The ID of the current record
     * @access public
     */    

    function get_id()
    {
        return $this->id;
    }
    
    /**
     * Returns the ID of the last record this Model inserted.
     *
     * @author md emran hasan <[email protected]>
     * @return int
     * @access public
     */    

    function get_insert_id()
    {
        return $this->__insert_id;
    }
    
    /**
     * Returns the number of rows returned from the last query.
     *
     * @author md emran hasan <[email protected]>
     * @return int
     * @access public
     */    

    function get_num_rows()
    {
        return $this->__num_rows;
    }
    
    /**
     * Returns the number of rows affected by the last query
     *
     * @author md emran hasan <[email protected]>
     * @return int
     * @access public
     */    

    function get_affected_rows()
    {
        return $this->__affected_rows;
    }
}
#5

[eluser]Référencement Google[/eluser]
Johan André, your model is very good, but when having such a complete model, why not then just to switch to a full ORM like Ignited Record ?
#6

[eluser]Johan André[/eluser]
[quote author="Too Pixel" date="1234770680"]Johan André, your model is very good, but when having such a complete model, why not then just to switch to a full ORM like Ignited Record ?[/quote]

First of all, I did not come up with most of the stuff in that model. Just so people don't think I take credit for something I did'nt invent! Smile

I really don't know why I don't use a complete ORM solution. It appeals to me having all relations setup nicely (like in Ignited record) but I guess I just been out of time to check it out. It sure looks good though...

By the way, can I use IR with Modular Extensions? Most of my work heavily relies on it... It also has some built-in validation, right? Can you still do "regular" CI-validation?
#7

[eluser]Référencement Google[/eluser]
I don't know but I think it will work as IR is almost a standalone library. You's better ask directly the author thought.
#8

[eluser]freshface[/eluser]
This is what I created:
Code:
&lt;?php

class Base_model extends Model
{

    /**
     * @author    Frederik Heyninck
     * @version 0.1
     */
    
    $table = '';
    
    function __construct($table)
    {
        parent::Model();
        $this->table = (string) $table;
    }
    
    /**
     * Insert
     *
     * @return    the last inserted id
     * @param    array
     */
    function insert($data = null)
    {
        $this->db-insert($this->table, $data);
        return $this->db->insert_id();
    }
    
    /**
     * Get Where
     *
     * @return    result
     * @param    array, int, int
     */
    
    function get_where($where = null, $limit = null, $offset = null)
    {
        return $this->db->get_where($this->table, $where, $limit, $offset);
    }
    
    /**
     * Update
     *
     * @return    void
     * @param    int, array
     */
    function update($id = null, $data = null)
    {
        $this->db-where('id', $id);
        $this->db-update($this->table, $data);
    }
    
    /**
     * Delete
     *
     * @return    void
     * @param    bool
     */
    function delete($id = null)
    {
        $this->db-where('id', $id);
        return $this->db-delete($this->table);
    }
    
    /**
     * Get all the records
     *
     * @return    void
     */
    function get_all()
    {
        $q = $this->db->get($this->table);
        return $q->result();
    }
    
    /**
     * Get one row
     *
     * @return    array
     * @param    int
     */
    function get_row($id = null)
    {
        $this->db-where('id', $id);
        $q = $this->db->get($this->table);
        return $q->row();
    }
    
    /**
     * Insert
     *
     * @return    int
     */
    function count_all()
    {
        return (int) $this->db->count_all_results($this->table);
    }
    
    function empty_table()
    {
        $this->db->empty_table($this->table);
    }

}

?&gt;

Usage:

Code:
class Test_model extends Base_model
{
    function __construct()
    {
        parent::Base_model('users');
    }
}


Regards
#9

[eluser]m4rw3r[/eluser]
IgnitedRecord is compatible with Modular Extensions (at least as long as you don't use the factory methods), but one issue (at least in previous versions) was that it couldn't load libs in subfolders (quite easy to fix, a file which incoudes ignitedrecord/Ignitedrecord.php).
Dunno how it is now, but that is the only problem as far as I can see.
#10

[eluser]ngocthai[/eluser]
Hi, Johan André, i have used your model, but has a problem:
"Call to a member function list_fields() on a non-object"

function load_table($table, $config = 'default')
{
if ($this->debug) log_message('debug', "Loading model table: $table");

$this->table = $table;
$this->use_dbconfig = $config;

$this->load->database($config);
$this->fields = $this->db->list_fields($table);

if ($this->debug)
{
log_message('debug', "Successfull Loaded model table: $table");
}
}
Please help me, thanks.




Theme © iAndrew 2016 - Forum software by © MyBB