了解PHP RESTful API

时间:2014-02-22 22:16:23

标签: php .htaccess api rest

我有以下XAMPP项目结构

xampp/htdocs/project
xampp/htdocs/project/index.php
xampp/htdocs/project/api/index.php

我也使用下面的.htaccess:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/api/index\.php(/|$)
RewriteRule ^/api/(.*)$ /api/index.php/$1 [QSA,L]

当我向api /发出Ajax请求时,我从api / index.php获得结果 但是,如果我想获得api / users /的示例呢?或者api / users / 5,其中5是ID。

2 个答案:

答案 0 :(得分:2)

首先将所有内容重写为单点即。 index.php,除了真实的现有资产,然后引入某种路由或路由器组件。

class Route{

private $routes = array();

public function addRoute($method, $url, $action){
    $this->routes[] = array('method' => $method, 
                          'url' => $url, 
                          'action' => $action
                          );
}

public function route(){
    $requestUrl = $_SERVER['REQUEST_URI'];
    $httpRequestMethod = $_SERVER['REQUEST_METHOD'];
    foreach($this->routes as  $route) {
        //convert route's variables with a regular expression
        $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['url'])) . "$@D";
        $matches = array();

        if($httpRequestMethod == $route['method'] && preg_match($pattern, $requestUrl, $matches)) {
            // remove the first match and just keet the extracted parameters
            array_shift($matches);
            // call specified controller's actions with the paramaters
            return call_user_func_array($route['action'], $matches);
        }
    }
}
}

class MyController{
    public function myAction($param)
    {
        //$this->render(), return Response(); etc. etc.
        echo $param; 
    }
}


class MyController2{
    public function myAction2($param)
    {
        //$this->render(), return Response(); etc. etc.
        echo $param; 
    }
}

$route = new Route();

$route->addRoute('GET', '/', 'MyController::myAction');
$route->addRoute('GET', '/resources/:id', 'MyController2::myAction2');

$route->route();

另外,请检查http://toroweb.org/

答案 1 :(得分:1)

当你完成时,你会有很多重写条目。但是这里应该对用户做出你想做的事情:

# /users/{id}
RewriteRule ^users/([0-9A-Za-z_\.-\@]+)$    users.php?id=$1 [QSA]

或者,如果您希望所有内容都通过索引:

# /users/{id}
RewriteRule ^users/([0-9A-Za-z_\.-\@]+)$    index.php?userid=$1 [QSA]

并且,如果您需要按请求类型(POST,GET,PUT等)进行区分:

RewriteCond %{REQUEST_METHOD} ="post" [NC]
RewriteRule ^users/([0-9]+)$  index.php?id=$1&method=add_user [QSA]