ubuntu 12.04 使用 composer 安装 Luracast Restler
Restler is a simple and effective multi-format Web API Server written in PHP.
Just deal with your business logic in php, restler will take care of the REST!
一、安装
使用 composer 安装 Luracast Restler. 也可以直接在 github 上 clone 或者下载到 zip 包.
github上的项目地址: https://github.com/Luracast/Restler
官方地址:(经常打不开) http://luracast.com/products/restler/
假定已经安装好了 composer, 如果没有安装 请先安装 composer.
# cd /var/www/ # sudo mkdir apiTest # cd apiTest/ # pwd /var/www/apiTest/ # sudo composer install
|--
|--
|--
|--
|--
|--
二、
(1),在 public 目录下创建 index.php 和自己的接口 php 文件(这里以 SayHello.php为例),
其它的接口文件类似 SayHello.php方式创建即可。
创建 index.php
# touch index.php 写入以下内容: <?php require_once '../vendor/restler.php'; use Luracast\Restler\Restler; use Luracast\Restler\Defaults; $r = new Restler(true, true); $r->addAPIClass('SayHello'); $r->addAPIClass('Resources'); $r->setSupportedFormats('JsonFormat', 'UploadFormat', 'JsFormat'); $r->handle();
创建 SayHello.php
# touch SayHello.php 写入以下内容: <?php /* * Let's say hello! * * 基本的实例,开始 Restler 3 之旅 */ class SayHello { /** * 带默认参数的问候 * * 返回 hello + 输入的问候语 * <br /> * author: * <br /> * 返回结果格式如下: * * @access public * @param string $to 问候语 * @return * */ public function hello($to='world') { return "Hello $to!"; } /** * 没有默认参数的问候,必须输入参数 * * 返回 hi + 输入的问候语 * <br /> * author: * <br /> * 返回结果格式如下: * * @access public * @param string $to 问候语 * @return * */ public function hi($to) { return "Hi $to!"; } }
(2), 将 /var/www/apiTest/vendor/luracast/explorer/ 下的 dist/ 目录
复制到 /var/www/apiTest/public/ 下 并重命名为 explorer/
# cp -r /var/www/apiTest/vendor/luracast/explorer/dist/ /var/www/apiTest/public/explorer/
三、nginx 配置
server { listen 80; server_name api.test.com; # change it to match your server name root /var/www/apiTest; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } // 这一个 if 判断很重要,如果缺少会出现 404 if ( !-e $request_filename ) { rewrite ^/public/(.*)$ /public/index.php?_REWRITE_COMMAND=$1; } location ~ \.php$ { try_files $uri = 404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } # log access_log /var/log/nginx/api_test.access.log; error_log /var/log/nginx/api_test.error.log; }
四、在浏览器中访问 http://api.advapi.com/public/explorer/index.html
http://api.test.com/public/explorer/index.html
五、问题和解决方法:
(1)200 : OK ../resources.json
在本机上没有配置虚拟主机, 直接用 localhost 访问,会出现 这个问题.
(2) 404 : Not Found ../resources.json
在 /var/www/apiTest/public/ 下没有 cache/ 目录.
或者 nginx 的配置文件里缺少如下的 if 判断:
if ( !-e $request_filename ) { rewrite ^/public/(.*)$ /public/index.php?_REWRITE_COMMAND=$1; }
(3) 500 : Internal Server Error ../resources.json
cache/ 目录没有可写权限.
解决方法:
在 /var/www/apiTest/public/ 下创建 cache/ 并设置为可写权限.
命令如下:
# cd /var/www/apiTest/public/ # sudo mkdir cache # sudo chmod -R 777 cache/
写下来作为记录,并且希望能够需要的童鞋.
ping -c 1 google.com | egrep -m1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'