restserver和restclient如何在CodeIgniter中一起工作

时间:2015-06-03 16:16:43

标签: php codeigniter rest-client codeigniter-restserver

如何设置我阅读教程http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814。但我无法理解,我想要更多细节。我是CodeIgniter和AP​​I的新手。

我从nettuts文章

执行了以下步骤
  • 下载restclient和restserver以及curl
  • 我尝试从rest-server运行示例,它没有向我显示任何内容。我加载自己的控制器和方法

1 个答案:

答案 0 :(得分:3)

  

REST SERVER:

这是侦听客户端(restClient)请求的服务器。 RESTServer有Request方法: POST()
GET()
PUT()
DELETE()

当你从RESTClient调用它时,请记住index_put();,请注意它们:

$this->index();

不是

$this->index_put(); //because restserver it self recognize the nature of request through header.

这是一个简单的例子:

RESTClient实现:

function request_test() {
        $this->load->library('rest', array(
            'server' => 'http://restserver.com/customapi/api/',
             //when not use keys delete these two liness below
            'api_key' => 'b35f83d49cf0585c6a104476b9dc3694eee1ec4e',
            'api_name' => 'X-API-KEY',
        ));
        $created_key = $this->rest->post('clientRequest', array(
            'id' => '1',
            'CustomerId' => '1',
            'amount' => '2450',
            'operatorName' => 'Jondoe',
        ), 'json');
        print_r($created_key);
        die;

    }
  • 确保您已加载休息库。
  

RESTSERVER:

<?php
require APPPATH . '/libraries/REST_Controller.php';

class api extends REST_Controller {
  public function clientRequest_post() {
    //to get header 
    $headers=array();
    foreach (getallheaders() as $name => $value) {
        $headers[$name] = $value;
    }
    //to get post data
    $entityBody = file_get_contents('php://input', 'r');
    parse_str($entityBody , $post_data);

    //giving response back to client 
    $this->response('success', 200);


  }
}
  

配置config/Rest.php

 //if you need no authentication see it's different option in the same file
    $config['rest_auth'] = false;

 //for enabling/disabling API_KEYS
$config['rest_enable_keys'] = FALSE;