原文地址:http://www.terrysco.com/node/drupal-as-mobile-backend.html
用Drupal很容易实现一个API,让手机平台或者其他系统使用json的格式进行通信。
<?php define('API_ERRORNO_INVALID_ACTION', 1); define('API_ERRORNO_INVALID_PARAM', 2); define('API_ERRORNO_NO_RECORD', 3); define('API_ERRORNO_INVALID_NAME', 4); define('API_ERRORNO_USER_BLOCKED', 5); define('API_ERRORNO_LOGIN_FAILED', 6); // 根据错误代码返回错误信息 function api_message_wrapper($errno) { $message = array( API_ERRORNO_INVALID_ACTION => '非法的请求动作', API_ERRORNO_INVALID_PARAM => '非法的请求参数', API_ERRORNO_NO_RECORD => '查找不到数据', API_ERRORNO_INVALID_NAME => '非法的手机号码', API_ERRORNO_USER_BLOCKED => '当前用户已经被禁用', API_ERRORNO_LOGIN_FAILED => '登陆失败', ); return isset($message[$errno]) ? $message[$errno] : '未知的错误'; } // 验证合法的action function api_action_route($action) { $valid_actions = array( 'login' => 'login', 'register' => 'register', 'getCardInfos' => 'get_card_info', ); return isset($valid_actions[$action]) ? $valid_actions[$action] : false; } function api_menu() { $items['api'] = array( 'page callback' => 'api_dispatch', 'access callback' => TRUE, //'access arguments' => array('使用API'), 'type' => MENU_CALLBACK, 'file' => 'api.functions.inc', ); return $items; } // 成功返回 function api_response_sucess($data) { drupal_json(array('ERRNO' => 0, 'DATA' => $data)); } // 失败返回 function api_response_error($errno) { if ($errno && is_numeric($errno)) { drupal_json(array( 'ERRNO' => $errno, 'MSG' => api_message_wrapper($errno), )); } } // API调度入口 function api_dispatch() { if (!isset($_POST['ACTION']) || !api_action_route($_POST['ACTION'])) { api_response_error(API_ERRORNO_INVALID_ACTION); } elseif (!isset($_POST['PARAM'])) { api_response_error(API_ERRORNO_INVALID_PARAM); } else { $param = json_decode($_POST['PARAM']); call_user_func('api_call_'. api_action_route($_POST['ACTION']), $param); } }
适用方法:
http://localhost/drupal/index.php?q=api
http://localhost/drupal/api