Not-Bad 2017-11-29 02:37 采纳率: 0%
浏览 1113

restful请求index方法时,真正请求的是index_get的方法,请教下源代码这块逻辑在哪。

请求的域名是:cidemo.com/Admin/RestfulController/index/2

但是走的是 Admin模块下的RestfulController控制器中的index_get 得方法

RestfulController控制器中我继承了REST_Controller

但是在REST_Controller 中我没发现将index 变成 index_get的逻辑啊。有哪位大神帮忙解答下

处理逻辑的控制器文件:

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

/**
 * Example
 *
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array.
 *
 */

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

class Restful extends REST_Controller
{
    function index_get($id = '')
    {

        var_dump($id);die;
        // Example data for testing.
        $widgets = array(
            1 => array('id' => 1, 'name' => 'sprocket'),
            2 => array('id' => 2, 'name' => 'gear')
        );

        if (!$id) {
            $id = $this->get('id');
        }
        if (!$id) {
            //$widgets = $this->widgets_model->getWidgets();
            if ($widgets)
                $this->response($widgets, 200); // 200 being the HTTP response code
            else
                $this->response(array('error' => 'Couldn\'t find any widgets!'), 404);
        }

        //$widget = $this->widgets_model->getWidget($id);
        $widget = @$widgets[$id]; // test code

        if ($widget)
            $this->response($widget, 200); // 200 being the HTTP response code
        else
            $this->response(array('error' => 'Widget could not be found'), 404);
    }

    function index_post()
    {
        $data = $this->_post_args;
        try {
            //$id = $this->widgets_model->createWidget($data);
            $id = 3; // test code
            //throw new Exception('Invalid request data', 400); // test code
            //throw new Exception('Widget already exists', 409); // test code
        } catch (Exception $e) {
            // Here the model can throw exceptions like the following:
            // * For invalid input data: new Exception('Invalid request data', 400)
            // * For a conflict when attempting to create, like a resubmit: new Exception('Widget already exists', 409)
            $this->response(array('error' => $e->getMessage()), $e->getCode());
        }
        if ($id) {
            $widget = array('id' => $id, 'name' => $data['name']); // test code
            //$widget = $this->widgets_model->getWidget($id);
            $this->response($widget, 201); // 201 being the HTTP response code
        } else
            $this->response(array('error' => 'Widget could not be created'), 404);
    }

    public function index_put()
    {
        $data = $this->_put_args;
        try {
            //$id = $this->widgets_model->updateWidget($data);
            $id = $data['id']; // test code
            //throw new Exception('Invalid request data', 400); // test code
        } catch (Exception $e) {
            // Here the model can throw exceptions like the following:
            // * For invalid input data: new Exception('Invalid request data', 400)
            // * For a conflict when attempting to create, like a resubmit: new Exception('Widget already exists', 409)
            $this->response(array('error' => $e->getMessage()), $e->getCode());
        }
        if ($id) {
            $widget = array('id' => $data['id'], 'name' => $data['name']); // test code
            //$widget = $this->widgets_model->getWidget($id);
            $this->response($widget, 200); // 200 being the HTTP response code
        } else
            $this->response(array('error' => 'Widget could not be found'), 404);
    }

    function index_delete($id = '')
    {

        // Example data for testing.
        $widgets = array(
            1 => array('id' => 1, 'name' => 'sprocket'),
            2 => array('id' => 2, 'name' => 'gear'),
            3 => array('id' => 3, 'name' => 'nut')
        );

        if (!$id) {
            $id = $this->get('id');
        }
        if (!$id) {
            $this->response(array('error' => 'An ID must be supplied to delete a widget'), 400);
        }

        //$widget = $this->widgets_model->getWidget($id);
        $widget = @$widgets[$id]; // test code

        if ($widget) {
            try {
                //$this->widgets_model->deleteWidget($id);
                //throw new Exception('Forbidden', 403); // test code
            } catch (Exception $e) {
                // Here the model can throw exceptions like the following:
                // * Client is not authorized: new Exception('Forbidden', 403)
                $this->response(array('error' => $e->getMessage()), $e->getCode());
            }
            $this->response($widget, 200); // 200 being the HTTP response code
        } else
            $this->response(array('error' => 'Widget could not be found'), 404);
    }

    public function response($info)
    {
        if (is_array($info)) {
            echo json_encode($info);
        }
    }

    public function index(){
        echo "this is index methods";
    }
}

继承的restful类文件:

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

class REST_Controller extends CI_Controller {

    private $method;
    private $format;

    private $get_args;
    private $put_args;
    private $args;

    // List all supported methods, the first will be the default format
    private $supported_formats = array(
        'xml'       => 'application/xml',
        'json'      => 'application/json',
        'serialize' => 'text/plain',
        'php'       => 'text/plain',
        'html'      => 'text/html',
        'csv'       => 'application/csv'
    );

    // Constructor function
    function __construct()
    {
        parent::__construct();

        // How is this request being made? POST, DELETE, GET, PUT?
        $this->method = $this->_detect_method();

        // Lets grab the config and get ready to party
        $this->load->config('rest');

        if($this->config->item('rest_auth') == 'basic')
        {
            echo "basic";
            $this->_prepareBasicAuth();
        }

        elseif($this->config->item('rest_auth') == 'digest')
        {
            echo "digest";
            $this->_prepareDigestAuth();
        }

        // Set up our GET variables
        $this->get_args = $this->uri->uri_to_assoc();//获取参数
        var_dump($this->get_args);

        // Set up out PUT variables
        var_dump(parse_str(file_get_contents('php://input'), $this->put_args));
        parse_str(file_get_contents('php://input'), $this->put_args);
        // Merge both for one mega-args variable
        $this->args = array_merge($this->get_args, $this->put_args);

        // Which format should the data be returned in?
        $this->format = $this->_detect_format();//设置参数方式  json 、 xml
    }

    /*
     * Remap
     *
     * Requests are not made to methods directly The request will be for an "object".
     * this simply maps the object and method to the correct Controller method.
     */
    function _remap($object_called)
    {
        $controller_method = $object_called.'_'.$this->method;

        if(method_exists($this, $controller_method))
        {
            $this->$controller_method();
        }

        else
        {
            show_404();
        }
    }

    /*
     * Responce
     *
     * Takes pure data and optionally a status code, then creates the responce
     */
    function responce($data = '', $http_code = 200)
    {
        $this->output->set_status_header($http_code);

        // If the method exists, call it
        if(method_exists($this, '_'.$this->format))
        {
            // Set a XML header
            $this->output->set_header('Content-type: '.$this->supported_formats[$this->format]);

            $formatted_data = $this->{'_'.$this->format}($data);
            $this->output->set_output( $formatted_data );
        }

        else
        {
            $this->output->set_output( $data );
        }
    }


    /*
     * Detect format
     *
     * Detect which format should be used to output the data
     */
    private function _detect_format()
    {
        if(array_key_exists('format', $this->args) && array_key_exists($this->args['format'], $this->supported_formats))
        {
            return $this->args['format'];
        }

        // If a HTTP_ACCEPT header is present...
        if($this->input->server('HTTP_ACCEPT'))
        {
            // Check to see if it matches a supported format
            foreach(array_keys($this->supported_formats) as $format)
            {
                if(strpos($this->input->server('HTTP_ACCEPT'), $format) !== FALSE)
                {
                    return $format;
                }
            }
        }

        // If it doesnt match any or no HTTP_ACCEPT header exists, uses the first (default) supported format
        list($default)=array_keys($this->supported_formats);
        return $default;
    }


    /*
     * Detect method
     *
     * Detect which method (POST, PUT, GET, DELETE) is being used
     */
    private function _detect_method()
    {
        $method = strtolower($this->input->server('REQUEST_METHOD'));
        if(in_array($method, array('get', 'delete', 'post', 'put')))
        {
            return $method;
        }

        return 'get';
    }


    // INPUT FUNCTION --------------------------------------------------------------

    public function get($key)
    {
        return array_key_exists($key, $this->get_args) ? $this->input->xss_clean( $this->get_args[$key] ) : $this->input->get($key) ;
    }

    public function post($key)
    {
        return $this->input->post($key);
    }

    public function put($key)
    {
        return array_key_exists($key, $this->put_args) ? $this->input->xss_clean( $this->put_args[$key] ) : FALSE ;
    }

    // SECURITY FUNCTIONS ---------------------------------------------------------

    private function _checkLogin($username = '', $password = NULL)
    {
        if(empty($username))
        {
            return FALSE;
        }

        $valid_logins =& $this->config->item('rest_valid_logins');

        if(!array_key_exists($username, $valid_logins))
        {
            return FALSE;
        }

        // If actually NULL (not empty string) then do not check it
        if($password !== NULL)
        {
            if($valid_logins[$username] != $password)
            {
                return FALSE;
            }
        }

        return TRUE;
    }

    private function _prepareBasicAuth()
    {
        $username = NULL;
        $password = NULL;

        // mod_php
        if (isset($_SERVER['PHP_AUTH_USER']))
        {
            $username = $_SERVER['PHP_AUTH_USER'];
            $password = $_SERVER['PHP_AUTH_PW'];
        }

        // most other servers
        elseif (isset($_SERVER['HTTP_AUTHENTICATION']))
        {
            if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']),'basic')===0)
            {
                list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
            }
        }

        if ( !$this->_checkLogin($username, $password) )
        {
            $this->_forceLogin();
        }

    }

    private function _prepareDigestAuth()
    {
        $uniqid = uniqid(""); // Empty argument for backward compatibility

        // We need to test which server authentication variable to use
        // because the PHP ISAPI module in IIS acts different from CGI
        if(isset($_SERVER['PHP_AUTH_DIGEST']))
        {
            $digest_string = $_SERVER['PHP_AUTH_DIGEST'];
        }
        elseif(isset($_SERVER['HTTP_AUTHORIZATION']))
        {
            $digest_string = $_SERVER['HTTP_AUTHORIZATION'];
        }
        else
        {
            $digest_string = "";
        }

        /* The $_SESSION['error_prompted'] variabile is used to ask
           the password again if none given or if the user enters
           a wrong auth. informations. */
        if ( empty($digest_string) )
        {
            $this->_forceLogin($uniqid);
            exit;
        }

        // We need to retrieve authentication informations from the $auth_data variable
        preg_match_all('@(username|nonce|uri|nc|cnonce|qop|response)=[\'"]?([^\'",]+)@', $digest_string, $matches);
        $digest = array_combine($matches[1], $matches[2]);

        if ( !array_key_exists('username', $digest) || !$this->_checkLogin($digest['username']) )
        {
            $this->responce(NULL, 401);
            exit;
        }

        $valid_logins =& $this->config->item('rest_valid_logins');
        $valid_pass = $valid_logins[$digest['username']];

        // This is the valid response expected
        $A1 = md5($digest['username'] . ':' . $this->config->item('rest_realm') . ':' . $valid_pass);
        $A2 = md5(strtoupper($this->method).':'.$digest['uri']);
        $valid_response = md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2);

        if ($digest['response'] != $valid_response)
        {
            $this->responce(NULL, 401);
            exit;
        }

    }


    private function _forceLogin($nonce = '')
    {
        header('HTTP/1.0 401 Unauthorized');
        header('HTTP/1.1 401 Unauthorized');

        if($this->config->item('rest_auth') == 'basic')
        {
            header('WWW-Authenticate: Basic realm="'.$this->config->item('rest_realm').'"');
        }

        elseif($this->config->item('rest_auth') == 'digest')
        {
            header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm'). '" qop="auth" nonce="'.$nonce.'" opaque="'.md5($this->config->item('rest_realm')).'"');
        }

        echo 'Text to send if user hits Cancel button';
        die();
    }

    // FORMATING FUNCTIONS ---------------------------------------------------------

    // Format XML for output
    private function _xml($data = array(), $structure = NULL, $basenode = 'xml')
    {
        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if (ini_get('zend.ze1_compatibility_mode') == 1)
        {
            ini_set ('zend.ze1_compatibility_mode', 0);
        }

        if ($structure == NULL)
        {
            $structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />");
        }

        // loop through the data passed in.
        foreach($data as $key => $value)
        {
            // no numeric keys in our xml please!
            if (is_numeric($key))
            {
                // make string key...
                //$key = "item_". (string) $key;
                $key = "item";
            }

            // replace anything not alpha numeric
            $key = preg_replace('/[^a-z0-9_-]/i', '', $key);

            // if there is another array found recrusively call this function
            if (is_array($value))
            {
                $node = $structure->addChild($key);
                // recrusive call.
                $this->_xml($value, $node, $basenode);
            }
            else
            {
                // add single node.

                $value = htmlentities($value, ENT_NOQUOTES, "UTF-8");

                $UsedKeys[] = $key;

                $structure->addChild($key, $value);
            }

        }

        // pass back as string. or simple xml object if you want!
        return $structure->asXML();
    }

    // Format HTML for output
    private function _html($data = array())
    {
        // Multi-dimentional array
        if(isset($data[0]))
        {
            $headings = array_keys($data[0]);
        }

        // Single array
        else
        {
            $headings = array_keys($data);
        }

        $this->load->library('table');

        $this->table->set_heading($headings);

        foreach($data as &$row)
        {
            $this->table->add_row($row);
        }

        return $this->table->generate();
    }

    // Format HTML for output
    private function _csv($data = array())
    {
        // Multi-dimentional array
        if(isset($data[0]))
        {
            $headings = array_keys($data[0]);
            $output = implode(',', $headings)."\r\n";

            foreach($data as &$row)
            {
                $output .= '"'.implode('","',$row)."\"\r\n";
            }
        }

        // Single array
        else
        {
            $headings = array_keys($data);
            $output = implode(',', $headings)."\r\n";
            $output .= '"'.implode('","',$data)."\"\r\n";
        }

        return $output;
    }

    // Encode as JSON
    private function _json($data = array())
    {
        return json_encode($data);
    }

    // Encode as Serialized array
    private function _serialize($data = array())
    {
        return serialize($data);
    }

    // Encode raw PHP
    private function _php($data = array())
    {
        return var_export($data);
    }


}
?>
  • 写回答

2条回答 默认 最新

  • 衫燃愚下 2017-11-29 05:41
    关注

    首先,贴代码
    看看你的RestfulController中@RequestMapping("/")是否有冲突

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧