好处
1:充分利用CI DB机制 ,避免手写SQL,造成SQL漏洞大量暴发
2:处理复杂逻辑与多表操作时,可以简化为单记录查询,逻辑结构会比较清晰,维护起来也简单,不用猜想别人写这个SQL语句包含有什么意义
3:不用每个人都不停地写SQL,从而可以节省不少时间
4:多次单条查询时,可以获得更好的查询缓存
核心思想,利用类的特性,以及CI->db数据的初始机制 result( “class”) row(1 , ‘class')
备注:这些机制在YII框架中实现的更充分,但是在CI中也有不错的实现
创建MY_Model.php
内容如下
<?php
class MY_Model extends CI_Model {
public $data ;
public function __construct(){
parent::__construct();
$this->table="" ;
}
public function __get($name) {
$CI = & get_instance();
if( isset( $CI->$name ) ) {
return $CI->$name ;
}
if (isset($this->data[$name])) {
return $this->data[$name];
}
$getter = "get" . ucfirst($name);
if (method_exists($this, $getter)) {
$this->data[ $name ] = $this->$getter();
return $this->data[ $name ];
}
}
public function r( $where =array(), $skip = 0 , $limit = 15 , $order_by_id = 'id' , $order_by="DESC" )
{
if( !empty( $where ) )
$this->db->where ( $where ) ;
$this->db->order_by( $order_by_id , $order_by ) ;
$this->db->limit( $limit , $skip ) ;
$this->db->from( $this->table ) ;
return $this->db->get() ;
}
public function r_count( $where = array() )
{
if( !empty( $where ) )
$this->db->where ( $where ) ;
$this->db->from( $this->table) ;
return $this->db->count_all_results();
}
}
相当于业务基类,提供r获取记录与获取记录数量的方法
业务model继承此类,获取会自动继承这些方法,在读取记录的时候,将会简便很多。
在循环或者使用单条记录的时候,需要利用result(‘class’) 或者row(1 , ‘class’) 来初始化记录数据到这个类上。就是说,自动给这个类附加变量元素,便于类在调用其它方法时使用。
但是类关系需要明确声明,如此便可以通过声明的关系调用其它的类。
<?php
class User_model extends MY_Model{
public function getDetail(){
$this->load->model('user_detail_model') ;
$where = array( 'user_id'=> $this->id ) ;
// print_r( $this->id ) ;
return $this->user_detail_model->r( $where , 0 , 1 )->row(1, 'user_detail_model' );
}
//---------------------------------------------
$this->load->model(‘user_model’) ;
$users = $this->user_model->r() ; //默认取头15行 ;
foreach( $users ->result(‘user_model’) as $user ) {
echo $user->name ;
echo $user->getDetail()->office ; //调用user model 中声明的detail ,当然这个detail model也需要创建好
}
技巧1:相对于数据库表来创建业务关系,最容易操作,因为我们所有的逻辑基础都是基于表关系的
技巧2:对于表关系的利用上,有时为了提高效率,避免对象初始化太多造成性能问题,可以多采用一下冗余字段,分表太多,维护上也是一个麻烦