我想根据输入的post参数验证请求。如果使用pre_controller无法获得帖子值。如果post_controller使用的控制器首先执行并向我显示验证错误。我想验证每个请求,所以不想在发布参数后手动在控制器中编写代码。 以下是代码, 文件:hooks.php
$hook['post_controller'][] = array(
'class' => 'Validate',
'function' => 'society',
'filename' => 'hooks.validate.php',
'filepath' => 'hooks',
'params' => array()
);
文件:hooks.validate.php
function society(){
$CI = & get_instance();
if($CI->is_hookable) {
$method = $CI->input->method();
$society_id = "";
if($method == 'get' || $method == 'GET')
{
$society_id = $CI->get('society_id');
}
if($method == 'post' || $method == 'POST')
{
$society_id = $CI->post('society_id');
}
if($society_id!="")
{
if(!is_society_exists($society_id))
{
$response['message'] = "Invalid or inactive society";
$response['status'] = false;
$CI->response($response, REST_Controller::HTTP_OK);
}
}
else
{
$response['message'] = "Unkown request";
$response['status'] = false;
$CI->response($response, REST_Controller::HTTP_OK);
}
}
}
答案 0 :(得分:0)
您想要的钩子是“ post_controller_constructor”,它在创建控制器之后但在执行之前发生。
$hook['post_controller_constructor'][] = array(
'class' => 'Validate',
'function' => 'society',
'filename' => 'hooks.validate.php',
'filepath' => 'hooks',
'params' => array()
);
这里有一些更简洁的代码(我认为)可以完成工作。
function society()
{
$CI = & get_instance();
if($CI->is_hookable)
{
//both input::post('item') and input::get('item')
//return NULL if the item is not found
//you don't need the following because NULL is empty too
//$society_id = "";
$method = $CI->input->method();
//use the variable as the method to call
$society_id = $CI->input->$method('society_id');
if( ! empty($society_id))
{
if( ! is_society_exists($society_id))
{
$response['message'] = "Invalid or inactive society";
}
}
else
{
$response['message'] = "Unkown request";
}
$response['status'] = false;
$CI->response($response, REST_Controller::HTTP_OK);
}
}
行
$society_id = $CI->input->$method('society_id');
将根据$CI->input->get('society_id')
返回的内容调用$CI->input->post('society_id')
或$CI->input->method()
,而无需一堆if/else
代码。