技术开发 频道

在CodeIgniter框架中使用RESTful服务

  步骤4 与现有应用整合

  在下载的示例程序中,我们刚才讲解了重要的部分,接下来讲解如何将下载程序中的关键类与现有的应用整合。下载的应用中,结构如下图:

与现有应用整合

  其实只需要把rest.php和libraries目录下的REST_Controller.php复制到你的应用中的相应位置即可。这里假设要从你的应用的后端实体模型中进行相关操作,并将操作发布成RESTful的webservice,因此修改代码如下:

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

class Api extends REST_Controller
{
    
function user_get()
    {
        
if(!$this->get('id'))
        {
            
$this->response(NULL, 400);
        }

        
$user = $this->user_model->get( $this->get('id') );

        
if($user)
        {
            
$this->response($user, 200); // 200 being the HTTP response code
        }

        
else
        {
            
$this->response(NULL, 404);
        }
    }

    
function user_post()
    {
        
$result = $this->user_model->update( $this->post('id'), array(
            
'name' => $this->post('name'),
            
'email' => $this->post('email')
        ));

        
if($result === FALSE)
        {
            
$this->response(array('status' => 'failed'));
        }

        
else
        {
            
$this->response(array('status' => 'success'));
        }

    }

    
function users_get()
    {
        
$users = $this->user_model->get_all();

        
if($users)
        {
            
$this->response($users, 200);
        }

        
else
        {
            
$this->response(NULL, 404);
        }
    }
}
?>

   以上的代码段其实之前都已经介绍过,只不过这次在每个方法中,读取的是后端数据库中的实体类而已。

0
相关文章