CI MY_Controller &MY_Model

<?php defined('BASEPATH') OR exit('No direct script access allowed');
 
class MY_Controller extends MX_Controller {

	/**
	 * 输出数据
	 *
	 * @var array
	 */
	var $_data = array();
	
	/**
	 * 是否使用缓存
	 *
	 * @var bool
	 */
	var $_cache = true;
	
	/**
	 * 默认缓存时间,单位秒
	 *
	 * @var int
	 */
	var $memcache_time = 60;
	
	/**
	 * 缓存键值标识前缀
	 *
	 * @var string
	 */
	var $_cache_key_prefix = '';

	
	public function __construct()
	{
		parent::__construct();
		
		$this->_data = array(
			'status' => 0,
			'data'	 => array()
		);
	
		//$this->load->library('Memcache');
		$this->load->helper('url');
		    	
		$this->load->library('form_validation');
		$this->form_validation->CI =& $this;
		/**
		 * $_REQUEST 参数校验
		 */
		$controller = $this->router->fetch_class();
		$method 	= $this->router->fetch_method();

		$rule_key 	= $controller.'/'.$method;
		$rule_key 	= strtolower($rule_key);
		
		log_message('debug', "apicheck ".$rule_key.":".json_encode($_REQUEST));
		$query_string = '';
		foreach ($_REQUEST as $k=>$q)
		{
			$query_string .= $k.'='.$q.'&';
		}
		log_message('debug', "apicheck ".$rule_key.":".$query_string);

		$request_validation_bool = $this->form_validation->getRuleByMethod($rule_key);
		if($request_validation_bool)
		{
			if (($this->form_validation->data_valid($rule_key,$this->_args)) === FALSE)
			{
				log_message('debug', "MY_Form_validation ".$rule_key." run false");
				$this->_data['data'] = $this->form_validation->get_error_array();
				$this->response($this->_data, 400);
			}
		}
		
		//加载redis基类
		if(REDIS_ON)
		{
			load_class('Redis', 'core');
		}
		
		//log_message('debug', 'appfront:http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]);
	}
	
	/**
	 * 更新记录
	 *
	 */
	public function update($data = array(), $return = false)
	{		
		if(empty($data))
		{
			//post数据
			$data = $this->input->post();
		}
		
		$item = array();
		
		$model = $this->getModel();
		
		//获取有效字段
		$param_keys = array_keys($data);
		$table_fields = $model->read('getTableFields',array());
		foreach ($param_keys as $k=>$field)
		{
			if(in_array($field,$table_fields))
			{
				$item[$field] = $data[$field];
			}
		}
				
		$this->_data = $model->write('update',$item);
	
		if($return)
		{
			return $this->_data;
		}
		else 
		{
			$this->response($this->_data, 200);
		}
	}
	
	/**
	 * 新增记录
	 *
	 */
	public function add($data = array(), $return = false)
	{		
		if(empty($data))
		{
			//post数据
			$data = $this->input->post();
		}
			
		$item = array();
		
		$model = $this->getModel();

		//获取有效字段
		$param_keys = array_keys($data);
		$table_fields = $model->read('getTableFields',array());
		foreach ($param_keys as $k=>$field)
		{
			if(in_array($field,$table_fields))
			{
				$item[$field] = $data[$field];
			}
		}
		
		$this->_data = $model->write('add',$item);
		
		if($this->_data['status'] == 1)
		{
			$key = $model->getKey();
			$this->_data['data']['insert_id'] = $this->_data['data'][$key];
		}
	
		if($return)
		{
			return $this->_data;
		}
		else 
		{
			$this->response($this->_data, 200);
		}
	}
	
	/**
	 * 获取记录
	 *
	 */
	public function getItem($id = 0)
	{				
		$model = $this->getModel();
		
		$key = $model->getKey();
		
		if(empty($id))
		{
			$id = $this->input->get_post($key);
		}
				
		$ret = $model->read('getItem',array($key => $id));
		
		if($ret)
		{
			$this->_data['data'] = $ret;
		}
		
		$this->_data['status'] = 1;
		
		$this->response($this->_data, 200);
	}
	
	/**
	 * 获取数据列表
	 *
	 */
	public function getItems($params = array(), $return  = false)
	{
		$offset 		= $this->input->get_post('offset');
		$limit			= $this->input->get_post('limit');
		
		if(empty($params))
		{
			$params 		= $this->input->get();
			if(empty($params))
			{
				$params 		= $this->input->post();
			}
		}

		if(isset($params['offset']))
		{
			unset($params['offset']);
		}
		
		if(isset($params['limit']))
		{
			unset($params['limit']);
		}
		
		$order_by = array();
		if(isset($params['order_by']))
		{
			$order_by = json_decode( urldecode($params['order_by']), true);
			unset($params['order_by']);
		}

		if(isset($params['where']))
		{
			if($params['where'])
			{
				$where = json_decode( urldecode($params['where']), true);
				log_message('debug','query:'.json_encode($where));
				$where_list = array();
				foreach ($where as $w => $wh)
				{
					$w = preg_replace('/ {1,}/', '|', trim($w));
					$where_list[$w] = $wh;
				}
				$params = array_merge($params, $where_list);
			}

			unset($params['where']);
		}

		$model = $this->getModel();
		
		//取params中有效的字段
		$table_fields = $model->getTableFields();
		if($params)
		{
			foreach ($params as $p => $v)
			{
				if(in_array($p, array('where', 'order_by')))
				{
					continue;	
				}
				
				$p = current(explode('|', $p));
				if(!in_array($p, $table_fields))
				{
					unset($params[$p]);
				}
			}
		}

		//对比表索引,取最优的索引
		$table_index_list 	= $model->getTableIndexFields();				//表索引列表
		$params_keys 		= $params ? array_keys($params) : array();							//参数字段列表
		
		$best_index = array();			//最优索引
		if($table_index_list)
		{
			$match_field_num = 0;			//匹配字段个数
			foreach ($table_index_list as $k => $tb_index)
			{
				$diff = array_diff($tb_index, $params_keys);
				
				if(empty($diff))
				{
					//有效索引
					if(count($diff) == count($tb_index))
					{
						//字段完全匹配,最优索引
						$best_index = $tb_index;
						break;
					}
					elseif(count($tb_index) > $match_field_num)
					{
						//更多字段匹配
						$best_index = $tb_index;
						$match_field_num = count($tb_index);
					}
				}
			}
		}
				
		//生成查询条件
		$where = array();
		if($best_index)
		{
			//设置最优索引查询条件
			foreach ($best_index as $i => $v)
			{
				$where[$v] = $params[$v];
				unset($params[$v]);
			}
			
			//设置其他参数
			if($params)
			{
				$where = array_merge($where, $params);
			}
		}
		else 
		{
			$where = $params;
		}

		$ret = array();
		$ret['count'] = $model->read('getTotal',array('where' => $where));
		
		//获取数据
		$list = $model->read('getItems',array(
						'where'		=> $where,
						'order_by'  => $order_by,
						'offset' 	=> $offset,
						'limit' 	=> $limit
					)
				);
		
		$ret['list'] = $list;
		
		//输出
		if($ret)
		{
			$this->_data['data'] = $ret;
		}
		
		$this->_data['status'] = 1;
		
		if($return)
		{
			return $this->_data;	
		}
		else 
		{
			$this->response($this->_data, 200);
		}
	}
	
	/**
	 * 删除记录
	 *
	 */
	public function delete()
	{						
		$model = $this->getModel();
		
		$key = $model->getKey();
		
		$id = $this->input->get_post($key);
		
		$item = $model->read('getItem',array($key => $id));
		if($item)
		{
			$this->_data = $model->write('delete',array($key => $id));
		}
		
		$this->response($this->_data, 200);
	}
	
	public function deleteByWhere()
	{
		$params 		= $_REQUEST;
		
		$model = $this->getModel();
		$key = $model->getKey();
		
		$ret = $this->getItems($params, 1);
		
		if($ret['status'] == 1 && $ret['data']['count'] > 0)
		{
			$ids = array();
			foreach ($ret['data']['list'] as $r => $item)
			{
				$ids[] = $item[$key];
			}
			
			$this->deleteByBatch($ids);
		}
		
		$this->_data['status'] = 1;
	
		$this->response($this->_data, 200);
	}
	
	public function deleteByBatch($ids = array())
	{			
		if(empty($ids))
		{		
			$ids = $this->input->post('ids');
				
			if($ids)
			{
				$ids  =  explode(',', $ids);
			}
		}
		

		if(empty($ids))
		{
			$this->response($this->_data, 200);
		}
		
		$model = $this->getModel();
		
		$key = $model->getKey();
		
		foreach ($ids as $k => $id)
		{		
			$item = $model->read('getItem',array($key => $id));
			if($item)
			{
				$this->_data = $model->write('delete',array($key => $id));
			}
		}
		
		$this->response($this->_data, 200);
	}
	
	
	public function truncateTable()
	{				
				
		$model = $this->getModel();
		
		$key = $model->getKey();
		
		$model->write('truncate', array());
		
		$this->_data['status'] = 1; 
		$this->response($this->_data, 200);
	}
	
	public  function initRedis()
	{
		$model = $this->getModel();
		
		$where = array();
		$items = $model->read('getItemsAll',$where);

		$model->read('initData',$items);
		exit;
	}
	
	public function response($data = null, $http_code = null)
	{
		header('Content-Type: application/json;charset=utf-8');
		echo json_encode($data);
		exit;
	}
		
}

<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * A base model to provide the basic CRUD actions for all models that inherit
 * from it.
 *
 */
class MY_Model extends CI_Model
{
	
	/**
	 * return data
	 *
	 * @var array
	 */
	public $_data = array();
	
	/**
	 * The database table to use, only set if you want to bypass the magic.
	 *
	 * @var string
	 */
	protected $_table;

	/**
	 * The primary key, by default set to `id`, for use in some functions.
	 *
	 * @var string
	 */
	protected $_primary_key = 'id';
	
	/**
	 * 表字段数组
	 *
	 * @var array
	 */
	protected $_fields = array();
	
	/**
	 * 表的索引数组
	 *
	 * @var array
	 */
	protected $_index_fields = array();
	
	/**
	 * 排序字段,默认取主键
	 *
	 * @var unknown_type
	 */
	protected $_sortby = array();

	/**
	 * Wrapper to __construct for when loading class is a superclass to a regular
	 * controller, i.e. - extends Base not extends Controller.
	 *
	 * @return void
	 * @author Jamie Rumbelow
	 */
	public function MY_Model()
	{
		$this->__construct();
	}

	/**
	 * The class constructor, tries to guess the table name.
	 *
	 * @author Jamie Rumbelow
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Set table name
	 *
	 * @param string $name The name for the table.
	 * @return string
	 */
	public function set_table_name($name = NULL)
	{
		return $this->_table = $name;
	}
}

/**
 * 组件基础model
 *
 */
class Base_Model extends MY_Model
{
	/**
	 * 模块名
	 *
	 * @var string
	 */
	public $_module;
	
	public $_redis_on = true;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->library('Hash_Data');
		
		//model 返回数据结构
		$this->_data = array(
			'status'=> 0,
			'data'	=> array()
		);
		
	}
		
	/**
	 * 读操作
	 *
	 * @param string $action 方法名
	 * @param array  $param  参数
	 */
	public function read($action, $param)
	{
		if (REDIS_ON && $this->_redis_on) //读redis数据
		{
			if (false !== strpos($action, 'search'))
			{
				$param['action'] = 'get'; //定义执行动作,get为获取结果
			}
			log_message('debug','redis set read'.$action);
			$res = $this->redisexec($action, $param);
			if (!empty($res))
			{
				log_message('debug','redis read'.$action);
				return $res;
			}
			
		}
				
		$res = $this->dbexec($action, $param); //读db数据

		//缓存查询结果,方法命中包含search,会自动执行搜索结果缓存
		if (false !== strpos($action, 'search'))
		{
			//搜索结果保存到redis
			$data['data']   = $res['data'];
			$data['param']  = $param;
			$data['action'] = 'save'; //定义执行动作,save为保存结果
			$res            = $this->redisexec($action, $data);
		}

		return $res;
	}
	 
	/**
	 * 写操作
	 *
	 * @param string $action 方法名
	 * @param array  $param  参数
	 */
	public function write($action, $param)
	{
		//写db数据
		$result = $this->dbexec($action, $param);
		if (REDIS_ON && $result['status'] && $this->_redis_on)
		{
			//写redis数据
			$result = $this->redisexec($action, $result['data']);
		}

		return $result;
	}
	
	/**
	 * 库操作
	 *
	 * @param string $model  模型
	 * @param string $action 方法名
	 * @param array  $param  参数
	 */
	private function dbexec($action, $param)
	{
		//返回数据
		$data = array(
			'status'=>0,
			'data'=>array()
		);
		
		if(method_exists($this, $action))
		{
			return call_user_func_array(array(
						&$this,
						$action
					), array($param));
		}
		else 
		{
			log_message('Debug','apicheck:'.$action.' is not exist');
		}
		
		return $data;
	}
	
	/**
	 * Redis操作
	 *
	 * @param string $action 方法名
	 * @param array  $param  参数
	 */
	private function redisexec($action, $param)
	{
		/* check redis model */
		list($path, $_model) = Modules::find(strtolower($this->_table.'_redis'), $this->_module, 'redis/');

		//redis model存在,加载
		if($path)
		{
			Modules::load_file($_model, $path);
			
			$model = ucfirst($_model);
			$class = new $model();
			$class->setTable($this->_table);
			$class->setFields($this->_fields);
			$class->setIndexFields($this->_index_fields);
			$class->setPrimarykey($this->_primary_key);
			$class->setSortBy($this->_sortby);
			if (!empty($action) && method_exists($class, $action))
			{
				return call_user_func_array(array(
					&$class,
					$action
				), array($param));
			}
		}
	}
	
	public function getTableIndexFields()
	{
		return $this->_index_fields;
	}
	
	/**
	 * 获取主键字段
	 *
	 * @return string
	 */
	public function getKey()
	{
		return $this->_primary_key;
	}
	
	/**
	 * 根据主键值获取单条记录
	 *
	 * @param array $param
	 * @return array
	 */
	function getItem($param = array())
	{
		if(is_array($param))
		{
			$id = $param[$this->_primary_key];
		}
		else 
		{
			$id = $param;
		}
		
		$this->db->where($this->_primary_key,$id);
		$item = $this->db->get($this->_table)->row_array();
		
		log_message('debug','querysql getitem:'.json_encode(array('sql'=>$this->db->last_query())));
		
		return $item;
	}
	
	/**
	 * 添加/更新数据
	 *
	 * @param array $param
	 * @return array
	 */
	function add($param = array())
	{
		//自增ID
		if(isset($param[$this->_primary_key]))
		{
			return $this->_data;
		}
		
		$ret = false;
		
		//新增
		$ret = $this->db->insert($this->_table,$param);
		log_message('debug','querysql insert:'.$this->db->last_query());
		if($ret)
		{
			$id = $this->db->insert_id();
		}
		
		if($ret)
		{
			$this->_data['status']	= 1;
			
			$param[$this->_primary_key] = $id;
			$this->_data['data']	= $param;
		}
		
		return $this->_data;
	}
	
	/**
	 * 添加/更新数据
	 *
	 * @param array $param
	 * @return array
	 */
	function update($param = array())
	{
		//自增ID
		$id = 0;
		if(!isset($param[$this->_primary_key]))
		{
			return $this->_data;
		}
		
		$id = $param[$this->_primary_key];
		
		$ret = false;

		//更新
		$this->db->where($this->_primary_key,$id);
		$ret = $this->db->update($this->_table,$param);
		log_message('debug','querysql update:'.json_encode(array('sql'=>$this->db->last_query())));

		if($ret)
		{
			$this->_data['status']	= 1;
			
			$param[$this->_primary_key] = $id;
			$this->_data['data']	= $param;
		}
		
		return $this->_data;
	}
	
	/**
	 * 删除
	 *
	 * @param array $ids		id集
	 * @return array
	 */
	function delete($param = array())
	{		
		$id 	= isset($param[$this->_primary_key]) ? $param[$this->_primary_key] : '';
		$where 	= isset($param['where']) ? $param['where'] : '';
		
		if($id)
		{			
			$this->db->where($this->_primary_key,$id);

		}
		
		if ($where)
		{
    		foreach ($where as $key =>$value)
    		{
				$this->_setDbWhere($key, $value);
    		}
		}
		
		if($id || $where)
		{
			if($this->db->delete($this->_table))
			{
				$this->_data['status'] = 1;
				$this->_data['data']	= $param;
			}
		}
		
		log_message('debug','querysql delete:'.json_encode(array('sql'=>$this->db->last_query())));
		
		return $this->_data;
	}
	
	/**
	 * 获取菜单数据列表
	 *
	 * @return array
	 */
	function getItems($param = array())
	{    	
		$where 	= isset($param['where']) ? $param['where'] : '';
		$orderby = isset($param['order_by']) ? $param['order_by'] : '';
		$offset = isset($param['offset']) ? $param['offset'] : 0;
		$limit 	= isset($param['limit']) ? $param['limit'] : 0;

    	if($where)
    	{
    		foreach ($where as $key =>$value)
    		{
				$this->_setDbWhere($key, $value);
    		}
    	}
    	
    	if($orderby)
    	{
    		$this->_sortby = $orderby;
    	}

    	if(empty($this->_sortby))
    	{
    		$this->db->order_by($this->_primary_key,'desc');
    	}
    	else 
    	{
    		foreach ($this->_sortby as $s => $by)
    		{
	    		$this->db->order_by($s,$by);
    		}
    	}
    	
    	if($limit)
    	{
    		$this->db->limit($limit,$offset);
    	}
    	
        $ret = $this->db->get($this->_table)->result_array();

        log_message('debug','querysql getitems:'.json_encode(array('sql'=>$this->db->last_query())));
        
        return $ret;
	}
	
	/**
	 * 获取数据表的所有数据
	 *
	 */
	function getItemsAll()
	{	
        return $this->db->get($this->_table)->result_array();
	}
	
	/**
	 * 获取记录总数
	 *
	 * @param array $param
	 * @return int
	 */
	function getTotal($param = array())
	{
		$where 	= isset($param['where']) ? $param['where'] : '';
		
    	if($where)
    	{
    		foreach ($where as $key =>$value)
    		{
				$this->_setDbWhere($key, $value);
    		}
    	}
    	    	
    	$this->db->from($this->_table);
        
    	$count =  $this->db->count_all_results();
    	
		log_message('debug','querysql gettotal:'.json_encode(array('sql'=>$this->db->last_query())));
		
    	return $count;
	}
	
	/**
	 * 获取表字段
	 *
	 * @return array()
	 */
	function getTableFields($param = array())
	{
		return $this->_fields;
	}
	
	/**
	 * 设置数据库查询类型
	 *
	 * @param string $key			字段名与操作符号 name|operate
	 * @param string/int/array $value
	 */
	function _setDbWhere($field_name,$value)
	{
		$list = explode('|',$field_name);
		
		//字段名
		$key = $list[0];
		
		//操作符
		$operate = '';
		if(count($list) > 1)
		{
			$operate = $list[1];
		}
		
		if(is_numeric($value))
		{
			$this->dataCompare($key, $value , $operate);
		}
		elseif(is_array($value) && $operate != 'mutil')
		{
			if($operate == '!=')
			{
				$this->db->where_not_in($key,$value);
			}
			else 
			{
				$this->db->where_in($key,$value);
			}		
		}
		else 
		{
			$this->dataCompare($key, $value , $operate);
		}
	}
	
	/**
	 * 变量比较
	 *
	 * @param var $a		变量a
	 * @param var $b		变量b
	 * @param var $comp		比较符
	 */
	private function dataCompare($a , $b ,$comp)
	{
		switch ($comp)
		{
			case '=': 	$this->db->where($a,$b);break;
			case '!=': 	$this->db->where($a.' !=',$b); break;
			case '>': 	$this->db->where($a.' >',$b);  break;
			case '<': 	$this->db->where($a.' <',$b); break;
			case '>=': 	$this->db->where($a.' >=',$b); break;
			case '<=': 	$this->db->where($a.' <=',$b); break;
			case 'dateformat>=': $this->db->where('DATE_FORMAT('.$a.' , \'%Y-%m-%d\') >=',$b);	break;		//DATE_FORMAT(service_time , \'%Y-%m-%d\')|>=
			case 'dateformat<=': $this->db->where('DATE_FORMAT('.$a.' , \'%Y-%m-%d\') <=',$b); 	break;		//DATE_FORMAT(service_time , \'%Y-%m-%d\')|<=
			case 'dateformat=': $this->db->where('DATE_FORMAT('.$a.' , \'%Y-%m-%d\') =',$b); 	break;		//DATE_FORMAT(service_time , \'%Y-%m-%d\')|<=
			case 'dateformath': $this->db->where('DATE_FORMAT('.$a.' , \'%Y-%m-%d %H\') =',$b); 	break;		//DATE_FORMAT(service_time , \'%Y-%m-%d\')|<=
			case 'like': 	$this->db->like($a,$b);	break;		//like
			case 'or': 	$this->db->or_where($a,$b);	break;		//or_where
			case 'in': 	$this->db->where_in($a,$b);	break;		//or_where
			case 'orin': 	$this->db->or_where_in($a,$b);	break;		//or_where
			case 'mutil': 	
			$query = array();
			foreach ($b as $k => $v)
			{
				$query[] = $k." like '%".str_replace('_', '\_', mysql_real_escape_string($v))."%'";
			}
			$sql = '(' . implode(' or ', $query) . ')';
			log_message('debug', 'query:'.$sql);
			$this->db->where($sql,  NULL, true);
			break;		//or_where
			default: $this->db->where($a,$b);break; 
		}
	}
}

/* End of file MY_Model.php */
/* Location: ./application/core/MY_Model.php */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值