从另一个应用程序通过http调用Yii RESTFul API


Call a Yii RESTFul API via http from another application

我有一个Yii应用程序,它已经在我创建的用户表上完成了CRUD。所以我已经有了一个视图、模型和控制器。现在我想创建一个具有JSON格式的RESTFul API,另一个应用程序可以调用它来创建用户。到目前为止,我的控制器中有以下代码,当我使用http请求对其进行本地测试时,这些代码可以工作。正如您在我的代码中看到的那样,$post数组具有硬编码的输入数据(仅用于测试目的),当我使用如下http请求在浏览器中调用RESTneneneba API时,它就工作了:

http://localhost/PregnancyApp/index.php/User/insert?

/User是控制器类,/insert是控制器内部的操作函数,如下所示:

//Here is the code that i have in my controller class
public function actionInsert(){
$post = array('email'=>'Ethel@example.com',
'password'=>'ethelpass',
'nickname'=>'Ethel',
'is_paid'=>'0',
'due_date'=>'2014-01-01',
'ios_token'=>'0011110000',
'serial_num'=>'1100001111',
'picture'=>'null'
);

$command = Yii::app()->db->createCommand('INSERT INTO user (email, password, 
nickname,is_paid, due_date,ios_token, serial_num, picture )
VALUES (:email, :password, :nickname, :is_paid, :due_date, :ios_token, :serial_num, 
:picture)');
$command->bindParam(':email', $post['email']);
$command->bindParam(':password', md5($post['password']));
$command->bindParam(':nickname', $post['nickname']);
$command->bindParam(':is_paid', $post['is_paid']);
$command->bindParam(':due_date', $post['due_date']);
$command->bindParam(':ios_token', $post['ios_token']);
$command->bindParam(':serial_num', $post['serial_num']);
$command->bindParam(':picture', $post['picture']);
json_encode($command->execute());
echo "Please, check your database if the entry registered";
}

因此,我的问题是,如何将这些值分配给http-post请求,以替换硬编码的$post数组?我希望(数组中的)输入值来自客户端应用程序。那么,如何格式化客户端应用程序可以发送的http post请求,以请求我的API创建用户呢?

您可以让make请求者以get或POST格式发送变量,然后您可以获得如下结果:

如果是帖子:

$post = array(
    'email' => $_POST['email'],
    'password' => $_POST['password'],
    'nickname'=> $_POST['nickname'],
    'is_paid'=>'0',
    'due_date'=>date('Y-m-d'),
    'ios_token'=> $_POST['ios_token'],
    'serial_num'=> $_POST['serial_num'],
    'picture'=>null
);

或获取

$post = array(
    'email' => $_GET['email'],

然后回显结果

echo CJSON::encode(array('result'=>'success'));

但是在使用之前不要忘记清理变量