步骤4:创建浏览器客户端
我们从为前端客户端设定新建文件夹开始。在你的Web服务器上的文件夹中创建一个名为simpletodo_client_browser的文件夹。完成后,创建一个index.php文件,并将下列代码写进去:
- <!DOCTYPE html>
- <html>
- <head>
- <title>SimpleTODO</title>
- <link rel="stylesheet" href="css/reset.css" type="text/css" />
- <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
- <script src="js/jquery.min.js"></script>
- <script src="js/jquery-ui-1.8.16.custom.min.js"></script>
- <style>
- body {
- padding-top: 40px;
- }
- #main {
- margin-top: 80px;
- text-align: center;
- }
- </style>
- </head>
- <body>
- <div class="topbar">
- <div class="fill">
- <div class="container">
- <a class="brand" href="index.php">SimpleTODO</a>
- </div>
- </div>
- </div>
- <div id="main" class="container">
- <form class="form-stacked" method="POST" action="login.php">
- <div class="row">
- <div class="span5 offset5">
- <label for="login_username">Username:</label>
- <input type="text" id="login_username" name="login_username" placeholder="username" />
- <label for="login_password">Password:</label>
- <input type="password" id="login_password" name="login_password" placeholder="password" />
- </div>
- </div>
- <div class="actions">
- <button type="submit" name="login_submit" class="btn primary large">Login or Register</button>
- </div>
- </form>
- </div>
- </body>
- </html>
这段代码的运行结果看起来就像这样:
SimpleTODO的登录页
需要注意的是我在这里已经包含了两个JavaScript文件和两个CSS文件:
- reset.css是你的标准CSS重置脚本。我使用了meyerweb.com css reset.
- bootstrap.min.css是Twitter Bootstrap
- jquery.min.js是最新版的jQuery library
- jquery-ui-1.8.16.custom.min.js是最新版的jQuery UI library
接下来,我们创建login.php文件来存储客户端会话中的用户名和密码。
- <?php
- //get the form values
- $username = $_POST['login_username'];
- $userpass = $_POST['login_password'];
- session_start();
- $_SESSION['username'] = $username;
- $_SESSION['userpass'] = $userpass;
- header('Location: todo.php');
- exit();
这里,我们简单地为用户开启一次会话,所依据的是用户所提供的用户名和密码组合。这充当了简单的组合密钥,它允许用户访问某个特定用户名和密码组合所存储的TODO项。然后我们重定向至todo.php,那里是我们开始与API服务器交互的地方。然而在我们开始编写todo.php文件之前,先创建一个 ApiCaller类,它将封装我们所需的全部API调用方法,包括请求的加密。
创建apicaller.php,并把下面的代码写进去:
- <?php
- class ApiCaller
- {
- //some variables for the object
- private $_app_id;
- private $_app_key;
- private $_api_url;
- //construct an ApiCaller object, taking an
- //APP ID, APP KEY and API URL parameter
- public function __construct($app_id, $app_key, $api_url)
- {
- $this->_app_id = $app_id;
- $this->_app_key = $app_key;
- $this->_api_url = $api_url;
- }
- //send the request to the API server
- //also encrypts the request, then checks
- //if the results are valid
- public function sendRequest($request_params)
- {
- //encrypt the request parameters
- $enc_request = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_app_key, json_encode($request_params), MCRYPT_MODE_ECB));
- //create the params array, which will
- //be the POST parameters
- $params = array();
- $params['enc_request'] = $enc_request;
- $params['app_id'] = $this->_app_id;
- //initialize and setup the curl handler
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $this->_api_url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, count($params));
- curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
- //execute the request
- $result = curl_exec($ch);
- //json_decode the result
- $result = @json_decode($result);
- //check if we're able to json_decode the result correctly
- if( $result == false || isset($result['success']) == false ) {
- throw new Exception('Request was not correct');
- }
- //if there was an error in the request, throw an exception
- if( $result['success'] == false ) {
- throw new Exception($result['errormsg']);
- }
- //if everything went great, return the data
- return $result['data'];
- }
- }
我们将利用ApiCaller类向我们的API服务器发送请求。这样,所有必需的加密和cURL初始化代码将会写在一个地方,我们就不用重复代码了。
- __construct函数接受三个参数:
- sendRequest()函数:
现在,我们开始写todo.php。首先,我们创建一些代码来为密码为test1234的用户nikko这是我们先前用来测试API服务器的那个用户名/密码组合)获取当前的todo项。
- <?php
- session_start();
- include_once 'apicaller.php';
- $apicaller = new ApiCaller('APP001', '28e336ac6c9423d946ba02d19c6a2632', 'http://localhost/simpletodo_api/');
- $todo_items = $apicaller->sendRequest(array(
- 'controller' => 'todo',
- 'action' => 'read',
- 'username' => $_SESSION['username'],
- 'userpass' => $_SESSION['userpass']
- ));
- echo '';
- var_dump($todo_items);
打开index.php,以nikko/tes1234登录,然后你应该看到我们先前创建的TODO项的avar_dump()。
恭喜,你已经成功地做好了一个向API服务器的API调用!在这段代码中,我们已经:
- 开启会话,使我们拥有了对$_SESSION中的username以及userpass的访问权
- 实例化了一个新的ApiCaller类,为其提供了APP ID,APP KEY,以及API服务器的URL
- 通过sendRequest()方法发送了一个请求
现在,我们来重新格式化一下数据,让它们开起来更好看些。向todo.php中添加下列HTML。别忘了移去var_dump()!
- <!DOCTYPE html>
- <html>
- <head>
- <title>SimpleTODO</title>
- <link rel="stylesheet" href="css/reset.css" type="text/css" />
- <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
- <link rel="stylesheet" href="css/flick/jquery-ui-1.8.16.custom.css" type="text/css" />
- <script src="js/jquery.min.js"></script>
- <script src="js/jquery-ui-1.8.16.custom.min.js"></script>
- <style>
- body {
- padding-top: 40px;
- }
- #main {
- margin-top: 80px;
- }
- .textalignright {
- text-align: right;
- }
- .marginbottom10 {
- margin-bottom: 10px;
- }
- #newtodo_window {
- text-align: left;
- display: none;
- }
- </style>
- <script>
- $(document).ready(function() {
- $("#todolist").accordion({
- collapsible: true
- });
- $(".datepicker").datepicker();
- $('#newtodo_window').dialog({
- autoOpen: false,
- height: 'auto',
- width: 'auto',
- modal: true
- });
- $('#newtodo').click(function() {
- $('#newtodo_window').dialog('open');
- });
- });
- </script>
- </head>
- <body>
- <div class="topbar">
- <div class="fill">
- <div class="container">
- <a class="brand" href="index.php">SimpleTODO</a>
- </div>
- </div>
- </div>
- <div id="main" class="container">
- <div class="textalignright marginbottom10">
- <span id="newtodo" class="btn info">Create a new TODO item</span>
- <div id="newtodo_window" title="Create a new TODO item">
- <form method="POST" action="new_todo.php">
- <p>Title:<br /><input type="text" class="title" name="title" placeholder="TODO title" /></p>
- <p>Date Due:<br /><input type="text" class="datepicker" name="due_date" placeholder="MM/DD/YYYY" /></p>
- <p>Description:<br /><textarea class="description" name="description"></textarea></p>
- <div class="actions">
- <input type="submit" value="Create" name="new_submit" class="btn primary" />
- </div>
- </form>
- </div>
- </div>
- <div id="todolist">
- <?php foreach($todo_items as $todo): ?>
- <h3><a href="#"><?php echo $todo->title; ?></a></h3>
- <div>
- <form method="POST" action="update_todo.php">
- <div class="textalignright">
- <a href="delete_todo.php?todo_id=<?php echo $todo->todo_id; ?>">Delete</a>
- </div>
- <div>
- <p>Date Due:<br /><input type="text" id="datepicker_<?php echo $todo->todo_id; ?>" class="datepicker" name="due_date" value="12/09/2011" /></p>
- <p>Description:<br /><textarea class="span8" id="description_<?php echo $todo->todo_id; ?>" class="description" name="description"><?php echo $todo->description; ?></textarea></p>
- </div>
- <div class="textalignright">
- <?php if( $todo->is_done == 'false' ): ?>
- <input type="hidden" value="false" name="is_done" />
- <input type="submit" class="btn" value="Mark as Done?" name="markasdone_button" />
- <?php else: ?>
- <input type="hidden" value="true" name="is_done" />
- <input type="button" class="btn success" value="Done!" name="done_button" />
- <?php endif; ?>
- <input type="hidden" value="<?php echo $todo->todo_id; ?>" name="todo_id" />
- <input type="hidden" value="<?php echo $todo->title; ?>" name="title" />
- <input type="submit" class="btn primary" value="Save Changes" name="update_button" />
- </div>
- </form>
- </div>
- <?php endforeach; ?>
- </div>
- </div>
- </body>
- </html>
PHP之友评论