Yii RESTFul与JSON格式更新和创建

时间:2014-04-14 10:02:14

标签: mysql json http rest yii

我正在尝试使用JSON格式在Yii框架中实现RESTFul。我有一个用户表,如下所示:

CREATE TABLE user(
    id int(10) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(64) NOT NULL,
    nickname VARCHAR(30) NOT NULL,
    PRIMARY KEY(id)
)Engine=InnoDB;

在我的Yii userController.php课程中(我的yii应用程序使用gii实现了CRUD) 我有以下两个基本上使用RESTful和JSON格式处理CRUD API的函数,如下所示:

public function actionRead($id=''){
    $requestType = Yii::app()->request->getRequestType();
    if($requestType !== 'GET' && $id === ''){
        throw new Exception('$id must be specified or acces this service with GET!');
        return;
    }

    if($id !== '0'){
        $user = Yii::app()->db->createCommand('SELECT * FROM user WHERE id=:id LIMIT 1');
        $user->bindParam(':id', $id);
        $user = $user->queryRow();
    }else{
        $user = Yii::app()->db->createCommand('SELECT * FROM user WHERE 1');
        $user = $user->queryAll();
    }

    echo json_encode($user);

}


public function actionSave($id){
    $requestType = Yii::app()->request->getRequestType();
    if($requestType !== 'POST'){
        throw new Exception('Acces this service with POST!');
        return;
    }

    $post = Yii::app()->request->getPost('form');

    if($id !== ''){//update...need help with logic here for update

    }else{//create...need help with logic here for create

    }

    $command = Yii::app()->db->createCommand('INSERT INTO user (id, email) VALUES (null, :email)');
    $command->bindParam(':email', $post['email']);


    return json_encode($command->execute());
}

使用上面的代码,我可以使用Google Chrome中的客户端查看和列出数据。但是我在获取更新和创建工作时遇到了麻烦。我已在评论中的上述代码中为"create""update"的两个实现添加了占位符。

我能否就如何实现这一目标获得一些想法或解决方案。

1 个答案:

答案 0 :(得分:0)

如果您有用户模型,那么您的代码将如下所示:

$post = Yii::app()->request->getPost('form');

if($id !== ''){//update...need help with logic here for update
     $model = User::model()->findByPk($id);
}else{//create...need help with logic here for create
     $model = new User;
}
$model->email = $post['email'];
$model->nickname = $post['nickname'];
$model->password = $post['password'];
$model->save();

return json_encode($model->id);

如果$ post包含属性数组。