步骤 2: 创建API服务器
既然我们是在开发一个以API为中心的应用,我们将创建两个“项目”: API 服务器,和前端客户端。 我们首先从创建API服务器开始。
在你的web server文件夹,创建一个文件夹,命名为simpletodo_api,然后创建一个index.php文件。这个index.php文件将作为一个访问API的前端控制器,所以,所有访问API服务器的请求都会由该文件产生。打开它并往里输入下列代码:
- <?php
- // 定义数据目录的路径
- define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
- //引入我们的models
- include_once 'models/TodoItem.php';
- //在一个try-catch块中包含所有代码,来捕获所有可能的异常!
- try {
- //获得在POST/GET request中的所有参数
- $params = $_REQUEST;
- //获取controller并把它正确的格式化使得第一个字母总是大写的
- $controller = ucfirst(strtolower($params['controller']));
- //获取action并把它正确的格式化,使它所有的字母都是小写的,并追加一个'Action'
- $action = strtolower($params['action']).'Action';
- //检查controller是否存在。如果不存在,抛出异常
- if( file_exists("controllers/{$controller}.php") ) {
- include_once "controllers/{$controller}.php";
- } else {
- throw new Exception('Controller is invalid.');
- }
- //创建一个新的controller实例,并把从request中获取的参数传给它
- $controller = new $controller($params);
- //检查controller中是否存在action。如果不存在,抛出异常。
- if( method_exists($controller, $action) === false ) {
- throw new Exception('Action is invalid.');
- }
- //执行action
- $result['data'] = $controller->$action();
- $result['success'] = true;
- } catch( Exception $e ) {
- //捕获任何一次样并且报告问题
- $result = array();
- $result['success'] = false;
- $result['errormsg'] = $e->getMessage();
- }
- //回显调用API的结果
- echo json_encode($result);
- exit();
实质上,这里我们创建的是一个简单的前端控制器,它实现了下列功能:
- 接受一次拥有任意个参数的API调用
- 为本次API调用抽取出Controller和Action
- 进行必要的检查确保Controller和Action都存在
- 执行API调用
- 捕获异常,如果有的话
- 返回一个结果给调用者
除了需要创建index.php外你还需要创建三个文件夹: controllers, models 和 data.
- controllers 文件夹存放的是所有我们API服务器将会用到的的控制器。我们用MVC架构来使API服务器结构更清楚合理。
- models 文件夹存放所有API服务器要用到的数据模型。
- data 文件夹将会用来保存API服务器的任何数据。
在controllers文件夹下创建一个叫Todo.php的文件。这将是任何TODO列表有关任务的控制器。按照TODO应用所需提供的功能,向Todo控制器里面添加必要的方法:
- <?php
- class Todo
- {
- private $_params;
- public function __construct($params)
- {
- $this->_params = $params;
- }
- public function createAction()
- {
- //create a new todo item
- }
- public function readAction()
- {
- //read all the todo items
- }
- public function updateAction()
- {
- //update a todo item
- }
- public function deleteAction()
- {
- //delete a todo item
- }
- }
现在为每个action中添加必要的功能实现。我将会提供createAction()方法的源码,其他方法将留作作业。如果你觉得毫无头绪,你也可以下载示例的源码,从那里拷贝。
- public function createAction()
- {
- //create a new todo item
- $todo = new TodoItem();
- $todo->title = $this->_params['title'];
- $todo->description = $this->_params['description'];
- $todo->due_date = $this->_params['due_date'];
- $todo->is_done = 'false';
- //pass the user's username and password to authenticate the user
- $todo->save($this->_params['username'], $this->_params['userpass']);
- //return the todo item in array format
- return $todo->toArray();
- }
在文件夹models下创建TodoItem.php,这样我们就可以创建“条目添加”的代码了。注意:我并没有和数据库进行连接,相反我将信息保存到文件中,虽然这可以用任何数据库来实现,但是 这样做相对来说要容易些。
- <?php
- class TodoItem
- {
- public $todo_id;
- public $title;
- public $description;
- public $due_date;
- public $is_done;
- public function save($username, $userpass)
- {
- //get the username/password hash
- $userhash = sha1("{$username}_{$userpass}");
- if( is_dir(DATA_PATH."/{$userhash}") === false ) {
- mkdir(DATA_PATH."/{$userhash}");
- }
- //if the $todo_id isn't set yet, it means we need to create a new todo item
- if( is_null($this->todo_id) || !is_numeric($this->todo_id) ) {
- //the todo id is the current time
- $this->todo_id = time();
- }
- //get the array version of this todo item
- $todo_item_array = $this->toArray();
- //save the serialized array version into a file
- $success = file_put_contents(DATA_PATH."/{$userhash}/{$this->todo_id}.txt", serialize($todo_item_array));
- //if saving was not successful, throw an exception
- if( $success === false ) {
- throw new Exception('Failed to save todo item');
- }
- //return the array version
- return $todo_item_array;
- }
- public function toArray()
- {
- //return an array version of the todo item
- return array(
- 'todo_id' => $this->todo_id,
- 'title' => $this->title,
- 'description' => $this->description,
- 'due_date' => $this->due_date,
- 'is_done' => $this->is_done
- );
- }
- }
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()结果
恭喜!您已经成功创建了一个的API服务器和API调用!
PHP之友评论