直接上完整代码,这个是最清楚的,数组设置验证规则。
public function addCar () {
$data = array (
'car_type_id' => $this ->input->post('car_type_id' ),
'car_no_type' => $this ->input->post('car_no_type' ),
'car_no' => $this ->input->post('car_no' ),
'frame_no' => $this ->input->post('frame_no' ),
'engine_no' => $this ->input->post('engine_no' ),
'remark' => $this ->input->post('remark' ),
);
$config = array (
array (
'field' => 'car_no' ,
'label' => '车牌号码' ,
'rules' => 'trim|required|min_length[5]' ,
),
array (
'field' => 'frame_no' ,
'label' => '车架号码' ,
'rules' => 'trim|required|exact_length[6]' ,
),
array (
'field' => 'engine_no' ,
'label' => '发动机号码' ,
'rules' => 'trim|required|exact_length[6]' ,
'errors' => array (
'required' => '这里可以输出你想显示的required错误信息' ,
'exact_length' => '这里可以输出你想显示exact_length的错误信息' ,
),
),
);
$this ->load->library('form_validation' );
$this ->form_validation->set_rules($config );
if ($this ->form_validation->run() == false ) {
$this ->outPutJson(5000 , array (), join($this ->form_validation->error_array()));
}
$insertId = $this ->CarManageModel->my_insert('car_info' , $data , TRUE );
if (!empty ($insertId )) {
$this ->outPutJson(200 , $data );
}
$this ->outPutJson(3008 );
}
final public function my_insert ($table = '' , $data , $returnInsertId = TRUE)
{
if (empty ($table ))
{
$table = $this ->table;
}
$this ->db->insert($table , $data );
if ($returnInsertId )
{
return $this ->db->insert_id();
}
}
public function outPutJson ($code = 0 , array $data = array() , $msg = '' )
{
$data = is_array($data ) ? $data : array ();
$this ->_formatoutPutData($data );
header('Content-Type:application/json; charset=utf-8' );
header('Cache-Control: no-cache, must-revalidate' );
header("Access-Control-Allow-Origin: {$this->config->item('allow_header')}" );
header('Access-Control-Allow-Credentials: true' );
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept" );
$msg = isset ($this ->_codeList[$code ]) ? $this ->_codeList[$code ] : $msg ;
exit (json_encode(array (
'data' => $data ,
'code' => intval($code ),
'msg' => $msg ,
)));
}
private function _formatoutPutData (array &$data )
{
if (is_array($data ) && !empty ($data )){
foreach ($data as $k => &$v ){
if (!is_array($v )){
$v = trim($v );
}else {
$this ->_formatoutPutData($v );
}
}
}
}
完整Controller类如下:
<?php
defined('BASEPATH' ) OR exit ('No direct script access allowed' );
class MY_Controller extends CI_Controller
{
protected $_codeList = array ();
protected $_apiCodeList = array ();
protected $_debug = FALSE ;
public $userToken = NULL ;
public $userSecret = NULL ;
public $adminUserId = 0 ;
public $isSuperAdmin = FALSE ;
public $roleId = 0 ;
const TEXT_NO_CONTENT = '请填写内容' ;
public function __construct ()
{
parent ::__construct();
$this ->load->config('siteinfo' );
$this ->load->library('Session' );
$this ->load->helpers('cookie' );
$this ->load->config('code_list' );
$this ->load->config('pass_access' );
$this ->_codeList = $this ->config->item('code_list' );
$this ->_codeList = $this ->_codeList + $this ->_apiCodeList;
$this ->_debug = $this ->input->post_get('__debug__' );
$this ->userToken = get_cookie('user_token' );
$this ->userSecret = get_cookie('user_secret' );
$passAccess = $this ->config->item('pass_access' );
foreach ($passAccess as $key => $v )
{
$passAccess [$key ] = strtolower($v );
}
$urlAction = strtolower($this ->router->class . '/' . $this ->router ->method );
$this ->adminUserId = $this ->_getUserIdByToken ();
$this ->isSuperAdmin = $this ->_isSuper ($this ->adminUserId );
$this ->roleId = $this ->_getUserInfo ('role_id ');
if (!in_array ($urlAction , $passAccess ) && !getenv ('LOGIN_DEBUG ')) //
{
if (!$this ->_isLogined())
{
$this ->outPutJson(409 );
}
}
}
public function outPutJson ($code = 0 , array $data = array() , $msg = '' )
{
$data = is_array($data ) ? $data : array ();
$this ->_formatoutPutData($data );
header('Content-Type:application/json; charset=utf-8' );
header('Cache-Control: no-cache, must-revalidate' );
header("Access-Control-Allow-Origin: {$this->config->item('allow_header')}" );
header('Access-Control-Allow-Credentials: true' );
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept" );
$msg = isset ($this ->_codeList[$code ]) ? $this ->_codeList[$code ] : $msg ;
exit (json_encode(array (
'data' => $data ,
'code' => intval($code ),
'msg' => $msg ,
)));
}
protected function _isLogined ()
{
if (empty ($this ->userToken) || empty ($this ->userSecret))
{
return FALSE ;
}
$this ->load->model('AdminUserModel' );
if ($this ->AdminUserModel->isLogined($this ->userToken, $this ->userSecret))
{
return TRUE ;
}
return FALSE ;
}
protected function _validate ($require = array() , $method = 'post' , $emptyRequire = array() )
{
if ($method == 'post' )
{
$posts = $this ->input->post();
}
elseif ($method == 'get' )
{
$posts = $this ->input->get();
}
if (empty ($posts ))
{
return self ::TEXT_NO_CONTENT;
}
if (!empty ($require ))
{
foreach ($require as $key => $value )
{
if (!isset ($posts [$key ]) || $posts [$key ] === '' ||
(is_array($posts [$key ]) && empty ($posts [$key ])) ||
(in_array($posts [$key ],$emptyRequire ) && empty ($posts [$key ]))
)
{
return $value ;
}
}
}
return TRUE ;
}
private function _formatoutPutData (array &$data )
{
if (is_array($data ) && !empty ($data )){
foreach ($data as $k => &$v ){
if (!is_array($v )){
$v = trim($v );
}else {
$this ->_formatoutPutData($v );
}
}
}
}
private function _getUserIdByToken ()
{
$this ->load->model('AdminUserModel' );
return $this ->AdminUserModel->getUserIdByToken($this ->userToken, $this ->userSecret);
}
private function _isSuper ($userId )
{
$this ->load->config('super_identity' );
$this ->load->model('AdminUserModel' );
$info = $this ->AdminUserModel->getUserInfo(array ('id' => $userId , 'is_deleted' => 0 , 'status' => 1 ), 'user_identity' );
if (!empty ($info ) && $info ['user_identity' ] === $this ->config->item('super_identity' ))
{
return TRUE ;
}
return FALSE ;
}
private function _getUserInfo ($field = '' )
{
$userId = $this ->_getUserIdByToken();
$fields = empty ($field ) ? 'username, system_id, ch_name, role_id' : $field ;
$info = $this ->AdminUserModel->getUserInfo(array ('id' => $userId , 'is_deleted' => 0 ), $fields );
if ($field )
{
return $info [$field ];
}
return $info ;
}
private function _checkAccess ($userId )
{
$urlAction = strtolower($this ->router->class . '/' . $this ->router ->method );
if ($this ->_isSuper ($userId ))
{
return TRUE ;
}
$this ->load->model('AdminUserModel' );
$userInfo = $this ->AdminUserModel->getUserInfo(array ('id' => $userId , 'is_deleted' => 0 , 'status' => 0 ), 'system_id,department_id,role_id,privilege_id' );
if (!empty ($userInfo ))
{
$this ->load->model('MenuModel' );
$menuWhere = array (
'module' => $urlAction ,
'is_deleted' => 0 ,
'status' => 1
);
$menuInfo = $this ->MenuModel->getMenuInfo($menuWhere , 'id' );
if (!empty ($userInfo ['privilege_id' ]))
{
$arrPrivilegeId = explode(',' , $userInfo ['privilege_id' ]);
if (!empty ($menuInfo ) && in_array($menuInfo ['id' ], $arrPrivilegeId ))
{
return TRUE ;
}
}
$this ->load->model('RoleModel' );
$this ->load->model('MenuModel' );
$roleWhere = array (
'id' => $userInfo ['role_id' ],
'system_id' => $userInfo ['system_id' ],
'department_id' => $userInfo ['department_id' ],
'is_deleted' => 0 ,
'status' => 1
);
$roleInfo = $this ->RoleModel->getRoleInfo($roleWhere , 'id' );
if (!empty ($roleInfo ))
{
$privilegeWhere = array (
'role_id' => $roleInfo ['id' ],
'is_deleted' => 0
);
$menuIds = $this ->RoleModel->getPrivileges();
if (!empty ($menuIds ) && in_array($menuInfo ['id' ], $menuIds ))
{
return TRUE ;
}
}
}
return FALSE ;
}
};
完整Model类:
<?php
defined('BASEPATH' ) OR exit ('No direct script access allowed' );
class MY_Model extends CI_Model
{
protected $_cachePrefix = 'bg_web' ;
public $table = '' ;
public function __construct ()
{
parent ::__construct();
$this ->load->database();
$this ->load->library('Session' );
$this ->load->config('siteinfo' );
$this ->_cachePrefix = $this ->_cachePrefix . '_' ;
}
final public function my_select ($table = '' , $where = '' , $field = '*' , $limit = '' , $like = array() , $order = '' , $key ='' , $group = '' )
{
if (empty ($table ))
{
$table = $this ->table;
}
if (!empty ($where ))
{
$where = $this ->db->where($where );
}
$field = str_replace("," , "," , $field );
$this ->db->select($field );
if (!empty ($like ) && is_array($like ))
{
$this ->db->like($like );
}
if (!empty ($limit ))
{
$limit_arr = explode("," , $limit );
if (count($limit_arr )==1 )
{
$this ->db->limit($limit );
}
else
{
$this ->db->limit($limit_arr [1 ], $limit_arr [0 ]);
}
}
if (!empty ($order ))
{
$this ->db->order_by($order );
}
if (!empty ($group ))
{
$this ->db->group_by($group );
}
$this ->db->from($table );
$datalist = array ();
$query = $this ->db->get();
if ($query ->num_rows() > 0 )
{
foreach ($query ->result_array() as $rs )
{
if ($key )
{
$datalist [$rs [$key ]] = $rs ;
}
else
{
$datalist [] = $rs ;
}
}
}
$query ->free_result();
return $datalist ;
}
final public function my_listPager ($table = '' , $where = array() , $field = '*' , $pageNo = 1 , $pageSize = 15 , $like = array() , $order = '' , $key = '' )
{
if (empty ($table ))
{
$table = $this ->table;
}
$data = array (
'list' => array (),
'page' => $pageNo ,
'total' => 0
);
$offset = ($pageNo -1 ) * $pageSize ;
if (!empty ($like ))
{
$this ->db->like($like );
}
$total = $this ->db->where($where )->count_all_results($table );
$result = $this ->my_select($table , $where , $field , "{$offset}, {$pageSize}" , $like , $order , $key );
if ($total > 0 )
{
$data = array (
'list' => $result ,
'total' => $total ,
'page' => $pageNo
);
}
return $data ;
}
final public function my_getOne ($table = '' , $where = '' , $field = '*' )
{
if (empty ($table ))
{
$table = $this ->table;
}
$info = $this ->my_select($table , $where , $field , '0, 1' );
if (!empty ($info ))
{
$info = $info [0 ];
}
return $info ;
}
final public function my_query ($sql )
{
return $this ->db->query($sql );
}
final public function my_insert ($table = '' , $data , $returnInsertId = TRUE)
{
if (empty ($table ))
{
$table = $this ->table;
}
$this ->db->insert($table , $data );
if ($returnInsertId )
{
return $this ->db->insert_id();
}
}
final public function my_update ($table = '' , $data , $where )
{
if (empty ($where ))
{
return FALSE ;
}
if (empty ($table ))
{
$table = $this ->table;
}
$this ->db->where($where );
if (is_array($data ))
{
foreach ($data as $k =>$v )
{
switch (substr($v , 0 , 2 )) {
case '+=' :
$this ->db->set($k , $k ."+" .str_replace("+=" ,"" ,$v ), false );
unset ($data [$k ]);
break ;
case '-=' :
$this ->db->set($k , $k ."-" .str_replace("-=" ,"" ,$v ), false );
unset ($data [$k ]);
break ;
case '<>' :
$this ->db->set($k , $k ."<>" .$v , false );
unset ($data [$k ]);
break ;
case '<=' :
$this ->db->set($k , $k ."<=" .$v , false );
unset ($data [$k ]);
break ;
case '>=' :
$this ->db->set($k , $k .">=" .$v , false );
unset ($data [$k ]);
break ;
case '^1' :
$this ->db->set($k , $k ."^1" , false );
unset ($data [$k ]);
break ;
case 'in' :
if (substr($v , 0 , 3 )=="in(" ){
$this ->db->where_in($k , $v , false );
unset ($data [$k ]);
break ;
}else {
break ;
}
default :
$this ->db->set($k , $v , true );
}
}
}
return $this ->db->update($table , $data );
}
final public function my_delete ($table = '' , $where )
{
if (empty ($where ))
{
return FALSE ;
}
if (empty ($table ))
{
$table = $this ->table;
}
return $this ->db->delete($table , $where );
}
final public function my_total ($table = '' , $where = '' )
{
if (empty ($table ))
{
$table = $this ->table;
}
$info = $this ->my_getOne($table , $where , "COUNT(*) AS n_total" );
return isset ($info ['n_total' ]) ? $info ['n_total' ] : 0 ;
}
final public function my_sum ($table = '' , $field , $where = '' )
{
if (empty ($table ))
{
$table = $this ->table;
}
$info = $this ->my_getOne($table , $where , "SUM({$field}) AS n_sum" );
return isset ($info ['n_sum' ]) ? $info ['n_sum' ] : 0 ;
}
final public function my_lastQuery ()
{
return $this ->db->last_query();
}
}