Code:
<?php
abstract class base_model extends Model
{
function base_model()
{
parent::Model();
}
/*** CRUD ***/
function create( $data, $return_keyfield_id )
{
// insert u tablicu
$this->db->insert( $this->get_table_name(), $this->strip_extra_data( $data ) );
if( $return_keyfield_id )
{
// vrati last insert id
$this->db->select_max( $return_keyfield_id );
$query = $this->db->get( $this->get_table_name() );
return $query->row(1)->$return_keyfield_id;
}
return true;
}
function read( $filter = array(), $sort = '', $fields = '*', $limit = 0, $offset = 0, $join = array(), $exclude = array() )
{
$this->db->select( $fields );
$db_filter = $this->get_filter( $filter );
$this->db->where( $db_filter[ 'where' ] );
$this->db->like( $db_filter[ 'like' ] );
if( $sort != '' )
{
$this->db->order_by( $sort );
}
if( $limit > 0 )
{
$this->db->limit( $limit, $offset );
}
if( count( $exclude ) )
{
$this->db->where_not_in( $exclude );
}
if( is_array( $join ) )
{
foreach( $join AS $join_table )
{
if( key_exists('table', $join_table) AND key_exists('child', $join_table) AND key_exists('parent', $join_table) )
{
$type = ( key_exists( 'type', $join_table ) ) ? $join_table[ 'type' ] : '';
$this->db->join
(
$join_table[ 'table' ],
$join_table[ 'child' ] . ' = ' . $join_table[ 'parent' ],
$type // left, right, outer, inner, left outer, right outer
);
}
}
}
$this->db->from( $this->get_table_name() );
$query = $this->db->get();
// return ovisno o limitu
if( $limit == 1 AND $query->num_rows() > 0 )
{
return $query->row();
}
else
{
return $query->result();
}
}
function update( $data, $filter )
{
$db_filter = $this->get_filter( $filter );
$this->db->where( $db_filter[ 'where' ] );
$this->db->like( $db_filter[ 'like' ] );
$this->db->update( $this->get_table_name(), $this->strip_extra_data( $data ) );
}
function delete( $filter )
{
$db_filter = $this->get_filter( $filter );
$this->db->where( $db_filter[ 'where' ] );
$this->db->like( $db_filter[ 'like' ] );
$this->db->delete( $this->get_table_name() );
}
/*** OTHER METHODS ***/
function get_max( $field )
{
$this->db->select_max( $field );
$query = $this->db->get( $this->get_table_name() );
return $query->row()->$field;
}
function row_exists( $field, $value )
{
$this->db->select( $field );
$this->db->where( array( $field => $value ) );
$query = $this->db->get( $this->get_table_name() );
return (bool)$query->num_rows;
}
/*** HELPERS ***/
function get_table_name()
{
return str_replace( '_model', '', get_class( $this ) );
}
function strip_extra_data( $data )
{
$data = $this->prepare_data( $data );
foreach( $data AS $prop => $field )
{
if( !property_exists( $this, $prop ) )
{
unset( $data[ $prop ] );
}
}
return $data;
}
function prepare_data( $data )
{
return $data;
}
/*** ABSTRACT FUNCTIONS ***/
// validates input data
abstract protected function validate_data( $data );
// creates filter array
abstract protected function get_filter( $filter );
}
?>