Comparing the Rest_controller and Ci_controller receiving parameters of CodeIgniter, the difference of output

Source: Internet
Author: User
Tags codeigniter

Rest_controller can be conveniently in the get/post/put/delete processing of relevant information, Ci_controller in the access time is the controller/method way, two kinds of each have advantages and disadvantages. So when necessary, although the restfull thought as the premise, but Ci_controller is also necessary to use. Although Rest_controller inherited from Ci_controller, but in the acquisition of input and output when a large number of encapsulation, if the use of Rest_controller for a long time, will forget the true nature of Ci_controller. Nonsense, here's a comparison of the most commonly used get and post: One, GET request Ci_controller's get

Under the Controller folder, create a new file test_ci.php, which reads as follows:

<?php


class Test_ci extends Ci_controller {public
    function Print_user ($name, $age =, $id = ' 3060411151 ', $w Ebsite) {
////        Mode 1
//        echo "name =". $name. "Age =". $age;        echo ' <br/> ';
////        mode 2
        $data = Array (' name ' => $name, ' age ' => $age, ' id ' => $id, ' website ' => $website);
        echo Json_encode ($data);
////        mode 3
//        $data = Array (' name ' => $name, ' age ' => $age);        $this->output->set_output (Json_encode ($data));

        Mode 4, Standard URL
//        parse_str ($_server[' query_string '), $_get);        $data = Array (' name ' =>$_get[' name '), ' age ' =>$_get[' age ', ' id ' =>$_get[' id ', ' website ' =>$_get[' Website ']);        Echo Json_encode ($data);
    }
}

The browser then enters http://app.sod90.com/city52/test_ci/print_user/yanzi/0/4567 for testing, and you see the normal JSON output.


We can sum up the following points:

1,CONTROLLDER/METHOD/PARAMS1/PARAMS2/PARAMS3 for security purposes, you must write a default value for each parameter in the method. This mode of transmission must be in order, in turn, CI in turn to match, can not be missed pass. In this case, if the/yanzi/67 is passed in, this 67 will be an age, not an ID.

2, when the request for get, and pass the parameter through CONTROLLDER/METHOD/PARAMS1/PARAMS2/PARAMS3, directly through the $_get[' name ' is not a value, through $this->input-> Get (' name ') is not the same as the value. The input parameter of the function is the parameter of the GET request.

3, when the return of the direct echo can be, of course, can also use $this->output->set_output, also can use Exit (). The common denominator is that the inside must be string, if the array to remember Json_encode.

4, this PathInfo URL advantage is conducive to SEO, can make the dynamic URL looks like static. The URL of this example is http://app.sod90.com/city52/test_ci/print_user/yanzi/25/4567 if I want to count ' Yanzi ' the number of times the name is accessed, you can directly parse the URLs. Whenever there are pros and cons, just think I want to pass a parameter website=http://blog.csdn.net/yanzi1225627, that URL address will be like this: http://app.sod90.com/city52/test_ci/ print_user/yanzi/25/4567/http://blog.csdn.net/yanzi1225627 with this pathinfo URL must kneel. The results obtained are as follows:


This is because CI distinguishes parameters by '/' to match them. To solve this problem, we can only use the traditional standard URL way, the method is also very simple:

1, call Parse_str ($_server[' query_string ', $_get) before calling _$get; Individual documents said also to the configuration file in the Uri_protocol change to path_info this is not necessary, directly with the default Request_uri can.

2, the original controller method of the input function all removed. The revised procedure is as follows:

<?php


class Test_ci extends Ci_controller {public
    function print_user (/* $name, $age =, $id = ' 3060411151 ', $website */) {
///        Mode 1
//        echo "name =". $name. "Age =". $age;        echo ' <br/> ';
////        Mode 2
//        $data = Array (' name ' => $name, ' age ' => $age, ' id ' => $id, ' website ' =>$ website);        Echo Json_encode ($data);
////        mode 3
//        $data = Array (' name ' => $name, ' age ' => $age);        $this->output->set_output (Json_encode ($data));

        Mode 4, Standard URL
        parse_str ($_server[' query_string '), $_get);
        $data = Array (' name ' =>$_get[' name '), ' age ' =>$_get[' age ', ' id ' =>$_get[' id ', ' website ' =>$_get[' website ' ]);
        echo Json_encode ($data);
    }
}
Run Results Sample:


Can see that the perfect solution to the problem. However, the direct use of $_get is not recommended, if the key does not exist will be an error. In fact, you can not enter Parse_str ($_server[' query_string '], $_get), which can be obtained directly by using $this->input->get (). The input and output of the Ci_controller GET request is introduced here.


Rest_controller's get

<?php
/**
 * Created by Phpstorm.
 * User:yanzi * DATE:15/11/20 * time
 : Morning 7:54 * *
require_once AppPath. ' libraries/rest_controller.php ';
Class Test_rest extends rest_controller{public
    function Index_get () {
        $data = array (
            ' name ' => $this- >get (' name '),
            ' age ' => $this->get (' age '),
            ' id ' => $this->get (' id ')
        );
        $this->response ($data);
    }
Browser input: http://app.sod90.com/city52/test_rest?name=yanzi&age=25&id=4567 can see the effect as follows:

Of course the code in the $this->get (' key '), can also be replaced by $this->input->get (' key '). In addition, our browser can also enter a paragraph-type URL test:

Http://app.sod90.com/city52/test_rest/name/yandzi/age/25/id/4567/format/json's results were disappointing:

Input Http://app.sod90.com/city52/test_rest?name/yandzi/age/25/id/4567/format/json, the result is still:

You can see that this is in the right way, but the parameters are not detected. Config from beginning to start

$config [' Uri_protocol'request_uri';
It's no good to change it to path_info. But Rest_controller's official website has the following description:

However, the verification did not succeed. I've tested both Apache and Nginx. I don't know if it's my environmental problem or what it is.


two, POST request Ci_controller Post Post requests are both simpler, ci_controller use $_post[' key ' or $this->input->post () to get parameters, Rest_ Controller use $this->post (' key ') to obtain.

Test code for the former:

    Public Function Print_user2 () {
        $data = array (' name ' =>$_post[' name '), ' age ' =>$_post[' age ', ' ID ' =>$_post [' ID '], ' website ' =>$_post[' website ']);
        echo Json_encode ($data);
    }
Test instance:


We replace the $_post[' name ' in the code with $this->input->post (' name '), and the result remains the same. But the only difference is that when you do not pass the ' name ' field, the $_post[' name ' is used directly to make an error, and the $this->input->post (' name ') gets null, so we should try to use $this-> Input->post () to get the parameters.

The code then changes to:

    Public Function Print_user2 () {
        $data = array (' name ' => $this->input->get (' name '), ' age ' =>$_post[' age ' ], ' id ' =>$_post[' id ', ' website ' =>$_post[' website ');
        echo Json_encode ($data);
    }
This is used to test a POST request with a parameter following the URL:

The discovery is OK. Then change the code, try to pass the parameters directly:

   Public Function Print_user2 ($name) {
        $data = array (' name ' => $name, ' age ' =>$_post[' age '), ' id ' =>$_post[' Id '], ' website ' =>$_post[' website ']);
        echo Json_encode ($data);
    }


The result is OK. But you enter the/name/yanziyan, you cannot distinguish the name field.

Rest_controller post test code:

<?php

/**
 * Created by Phpstorm.
 * User:yanzi * DATE:15/11/20 * time
 : Morning 7:54 * *
require_once AppPath. ' libraries/rest_controller.php ';
Class Test_rest extends rest_controller{public
    function Index_get () {
        $data = array (
            ' name ' => $this- >get (' name '),
            ' age ' => $this->get (' age '),
            ' id ' => $this->get (' id ')
        );
        $this->response ($data);
    }

    Public Function Index_post () {
        $data = array (
            ' name ' => $this->post (' name '),
            ' age ' => $this- >post (' age '),
            ' id ' => $this->post (' id ')
        );
        $this->response ($data);
    }
To test using Post_man:


And then test the example of getting a get parameter in the POST request:

    Public Function Index_post () {
        $data = array (
            ' name ' => $this->get (' name '),
            ' age ' => $this-> Post (' Age '),
            ' id ' => $this->post (' id ')
        );
        $this->response ($data);
    }

You can see that the name parameter is not received.
But don't be afraid, replace $this->get () with $this->input->get () Try:

    Public Function Index_post () {
        $data = array (
            ' name ' => $this->input->get (' name '),
            ' age ' =>$ This->post (' age '),
            ' id ' => $this->post (' id ')
        );
        $this->response ($data);
    }

Test:


So you can get the parameters. In addition, using $this->query () can also be used to obtain the URL parameters to the post. However, query is not getting the post parameters.

Again to test the way the next/key/params, found still not:




The final conclusion is as follows:

1, it needs to be clear that $this->input->get () and $this->input->post () are the methods provided by Ci_controller, Rest_controller inherit from Ci_ Controller In addition to these two methods, the author provides us with a more convenient way to access: $this->get (), $this->post (), $this->query ().

2, it is not recommended to use _$get and _$post to obtain parameters, because the field is not transmitted will be an error. In Ci_controller If you use _$get (only if you use KEY=PARAMS1&KEY2=PARAMS2 this way to pass parameters), add: Parse_str ($_server[' query_string '), $_ Get);

3,ci_controller and Rest_controller These two controllers differ greatly in access. Rest is automatically routed to you according to the type of request Get/post to Xxx_get () and Xxx_post (), only the name of the controller is required in the URL, the name of method is not required, CI is required to specify the function name in the URL ***/controller/method /params1/params2/params3

4,ci_controller is to support the ***/controller/method/params1/params2/params3 of this piecewise URL, to method this function in order to pass the data, but if the parameter itself/there will be a problem. So you have to use ***/CONTROLLER/METHOD?KEY1=PARAMS1&KEY2=PARAMS2 this way when you need to.

5,rest_controller does not support ***/CONTROLLER/METHOD/PARAMS1/PARAMS2/PARAMS3, but the official online said support/controller/key1/params1/key2/ PARAMS2, but I was unsuccessful on both Nginx and Apache.

6, $this->query can be used under rest controller to get the parameters (? key=params1&key2=params2) in the URL, whether it is a getting request. is also the parameter that is passed in the URL of the post or put request. Of course, the POST request can also be $this->input->get () to obtain the parameters in the URL, through the $this->get () in the POST request is not get the parameters in the URL.

7, $this->output->set_output () is a method provided by Ci_controller, but it can be returned directly $this->response () in rest. You can use Echo or exit to return data directly in Ci_controller if the $this->output->set_output () is too long and only back data is considered.


2015-12-23 Supplementary Note:

1,rest API does not support the extraction of multiple parameters at a time, only a single fetch: $this->get (' Key1 '), there is no way to $this->get (Array (' Key1 ', ' Key2 '));

2,codeigniter support to remove multiple parameters at once, but must add input, such as: $this->input->get (' field1 ', ' field2 ');

See also: http://codeigniter.org.cn/user_guide/libraries/input.html


Reference documents:

1,restserver Github:https://github.com/chriskacerguis/codeigniter-restserver

2,restserver guide:http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814

3,codeigniter Official website: http://codeigniter.org.cn/user_guide/libraries/output.html


------------------Welcome to join the PHP CodeIgniter community Group: 460132647, note yanzi


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.