PHP头条
热点:

步骤 2: 创建API服务器

既然我们是在开发一个以API为中心的应用,我们将创建两个“项目”: API 服务器,和前端客户端。 我们首先从创建API服务器开始。

在你的web server文件夹,创建一个文件夹,命名为simpletodo_api,然后创建一个index.php文件。这个index.php文件将作为一个访问API的前端控制器,所以,所有访问API服务器的请求都会由该文件产生。打开它并往里输入下列代码:

  1. <?php  
  2. // 定义数据目录的路径  
  3. define('DATA_PATH'realpath(dirname(__FILE__).'/data'));  
  4.  
  5. //引入我们的models  
  6. include_once 'models/TodoItem.php';  
  7.  
  8. //在一个try-catch块中包含所有代码,来捕获所有可能的异常!  
  9. try {  
  10.     //获得在POST/GET request中的所有参数  
  11.     $params = $_REQUEST;  
  12.       
  13.     //获取controller并把它正确的格式化使得第一个字母总是大写的  
  14.     $controller = ucfirst(strtolower($params['controller']));  
  15.       
  16.     //获取action并把它正确的格式化,使它所有的字母都是小写的,并追加一个'Action'  
  17.     $action = strtolower($params['action']).'Action';  
  18.  
  19.     //检查controller是否存在。如果不存在,抛出异常  
  20.     iffile_exists("controllers/{$controller}.php") ) {  
  21.         include_once "controllers/{$controller}.php";  
  22.     } else {  
  23.         throw new Exception('Controller is invalid.');  
  24.     }  
  25.       
  26.     //创建一个新的controller实例,并把从request中获取的参数传给它  
  27.     $controller = new $controller($params);  
  28.       
  29.     //检查controller中是否存在action。如果不存在,抛出异常。  
  30.     if( method_exists($controller$action) === false ) {  
  31.         throw new Exception('Action is invalid.');  
  32.     }  
  33.       
  34.     //执行action  
  35.     $result['data'] = $controller->$action();  
  36.     $result['success'] = true;  
  37.       
  38. } catch( Exception $e ) {  
  39.     //捕获任何一次样并且报告问题  
  40.     $result = array();  
  41.     $result['success'] = false;  
  42.     $result['errormsg'] = $e->getMessage();  
  43. }  
  44.  
  45. //回显调用API的结果  
  46. echo json_encode($result);  
  47. exit();  

实质上,这里我们创建的是一个简单的前端控制器,它实现了下列功能:

  • 接受一次拥有任意个参数的API调用
  • 为本次API调用抽取出Controller和Action
  • 进行必要的检查确保Controller和Action都存在
  • 执行API调用
  • 捕获异常,如果有的话
  • 返回一个结果给调用者

除了需要创建index.php外你还需要创建三个文件夹:  controllers, models 和  data.

API server folders 

  • controllers  文件夹存放的是所有我们API服务器将会用到的的控制器。我们用MVC架构来使API服务器结构更清楚合理。
  • models 文件夹存放所有API服务器要用到的数据模型。
  • data 文件夹将会用来保存API服务器的任何数据。

在controllers文件夹下创建一个叫Todo.php的文件。这将是任何TODO列表有关任务的控制器。按照TODO应用所需提供的功能,向Todo控制器里面添加必要的方法:

  1. <?php  
  2. class Todo  
  3. {  
  4.     private $_params;  
  5.       
  6.     public function __construct($params)  
  7.     {  
  8.         $this->_params = $params;  
  9.     }  
  10.       
  11.     public function createAction()  
  12.     {  
  13.         //create a new todo item  
  14.     }  
  15.       
  16.     public function readAction()  
  17.     {  
  18.         //read all the todo items  
  19.     }  
  20.       
  21.     public function updateAction()  
  22.     {  
  23.         //update a todo item  
  24.     }  
  25.       
  26.     public function deleteAction()  
  27.     {  
  28.         //delete a todo item  
  29.     }  
  30. }  
  31.  

现在为每个action中添加必要的功能实现。我将会提供createAction()方法的源码,其他方法将留作作业。如果你觉得毫无头绪,你也可以下载示例的源码,从那里拷贝。

  1. public function createAction()  
  2. {  
  3.     //create a new todo item  
  4.     $todo = new TodoItem();  
  5.     $todo->title = $this->_params['title'];  
  6.     $todo->description = $this->_params['description'];  
  7.     $todo->due_date = $this->_params['due_date'];  
  8.     $todo->is_done = 'false';  
  9.       
  10.     //pass the user's username and password to authenticate the user  
  11.     $todo->save($this->_params['username'], $this->_params['userpass']);  
  12.       
  13.     //return the todo item in array format  
  14.     return $todo->toArray();  
  15. }  
  16.  

在文件夹models下创建TodoItem.php,这样我们就可以创建“条目添加”的代码了。注意:我并没有和数据库进行连接,相反我将信息保存到文件中,虽然这可以用任何数据库来实现,但是 这样做相对来说要容易些

  1. <?php  
  2. class TodoItem  
  3. {  
  4.     public $todo_id;  
  5.     public $title;  
  6.     public $description;  
  7.     public $due_date;  
  8.     public $is_done;  
  9.       
  10.     public function save($username$userpass)  
  11.     {  
  12.         //get the username/password hash  
  13.         $userhash = sha1("{$username}_{$userpass}");  
  14.         ifis_dir(DATA_PATH."/{$userhash}") === false ) {  
  15.             mkdir(DATA_PATH."/{$userhash}");  
  16.         }  
  17.           
  18.         //if the $todo_id isn't set yet, it means we need to create a new todo item  
  19.         ifis_null($this->todo_id) || !is_numeric($this->todo_id) ) {  
  20.             //the todo id is the current time  
  21.             $this->todo_id = time();  
  22.         }  
  23.           
  24.         //get the array version of this todo item  
  25.         $todo_item_array = $this->toArray();  
  26.           
  27.         //save the serialized array version into a file  
  28.         $success = file_put_contents(DATA_PATH."/{$userhash}/{$this->todo_id}.txt", serialize($todo_item_array));  
  29.           
  30.         //if saving was not successful, throw an exception  
  31.         if$success === false ) {  
  32.             throw new Exception('Failed to save todo item');  
  33.         }  
  34.           
  35.         //return the array version  
  36.         return $todo_item_array;  
  37.     }  
  38.       
  39.     public function toArray()  
  40.     {  
  41.         //return an array version of the todo item  
  42.         return array(  
  43.             'todo_id' => $this->todo_id,  
  44.             'title' => $this->title,  
  45.             'description' => $this->description,  
  46.             'due_date' => $this->due_date,  
  47.             'is_done' => $this->is_done  
  48.         );  
  49.     }  
  50. }  
  51.  

createAction方法使用到TodoItem模型里面两个方法:

  • save() – 该方法将TodoItem保存到一个文件中,如有必要,需要设置todo_id。
  • toArray() – 该方法返回一个以变量为索引的数组Todo条目。

由于API需要通过HTTP请求调用,在浏览器输入如下地址测试API:

http://localhost/simpletodo_api/?controller=todo&action=create&title=test%20title&description=test%20description&due_date=12/08/2011&username=nikko&userpass=test1234

如果没有错,你应该在data文件夹下看到一个新的文件夹,在该文件夹里面有一个文件,文件内容如下:

createAction() result 

createAction()结果

恭喜!您已经成功创建了一个的API服务器和API调用!


www.phpzy.comtrue/php/20947.htmlTechArticle步骤 2: 创建 API服务器 既然我们是在开发一个以API为中心的应用,我们将创建两个项目: API 服务器 ,和 前端客户端 。 我们首先从创建API服务器开始。 在...

相关文章

PHP之友评论

今天推荐