CodeIgniter Rest API(Phil Sturgeon) - 如何砍掉一个非常大的api文件

时间:2013-05-12 17:46:15

标签: api codeigniter rest

我一直在构建一个休息api(使用Phil Sturgeons Codeigniter-Restserver),并且我一直坚持使用以下教程:

http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

特别是我一直在关注本教程的这一部分:

function user_get()  
{  
    // respond with information about a user  
}  

function user_put()  
{  
    // create a new user and respond with a status/errors  
}  

function user_post()  
{  
    // update an existing user and respond with a status/errors  
}  

function user_delete()  
{  
    // delete a user and respond with a status/errors  
}

我一直在为api可访问的每个数据库对象编写上述函数,并且还:

function users_get()  //    <-- Note the "S" at the end of "user"
{  
    // respond with information about all users
} 

我目前有大约30个数据库对象(用户,产品,客户端,事务等),所有这些对象都有为其编写的上述函数,并且所有函数都被转储到/controllers/api/api.php中,并且这个文件现在已经变得非常大(超过2000行代码)。

问题1:

有没有办法将这个api文件拆分成30个文件,例如,将所有与单个数据库对象相关的api函数放在一个地方,而不是仅将所有api函数转储到一个文件中?

问题2:

我还希望将当前模型函数(非api相关函数)与api使用的函数分开。
我应该这样做吗? 我应该在这里使用推荐的方法吗?例如,我应该编写api使用的单独模型,还是可以保留同一文件中给定数据库对象的所有模型函数(非api函数和api函数)?

任何反馈或建议都会很棒..

1 个答案:

答案 0 :(得分:3)

您可以像创建常规控制器一样创建api控制器;你可以对模特做同样的事情。

application/controllers/api/users.php

class Users extends REST_Controller{
    function user_post(){
        $this->users_model->new_user()
    ...

 POST index.php/api/user

-

application/controllers/api/transactions.php

class Transactions extends REST_Controller{
    function transaction_get(){
        $this->transactions_model->get()
    ...

GET index.php/api/transaction
  

我还希望将当前模型函数(非api相关函数)与api使用的函数分开。

我不明白为什么你不能使用相同的方法,只要它们返回你需要的东西。