当前位置: 动力学知识库 > 问答 > 编程问答 >

.htaccess - Understanding a PHP RESTful API

问题描述:

I have the following XAMPP project structure

xampp/htdocs/project

xampp/htdocs/project/index.php

xampp/htdocs/project/api/index.php

I also use the folowing .htaccess :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/api/index\.php(/|$)

RewriteRule ^/api/(.*)$ /api/index.php/$1 [QSA,L]

When I make an Ajax request to api/, I get the results from api/index.php

But what if I want to get the examples for api/users/? or api/users/5 where 5 is the ID.

网友答案:

By the time you are done, you'll have quite a lot of rewrite entries. But here's one that should do what you want with respect to users:

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

or, if you want everything to pass through index:

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

and, if you need to differentiate by request type (POST, GET, PUT, etc):

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

First rewrite all to the single point ie. index.php, except the real existing assets, then introduce some kind of routing or a router component.

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'])) . "[email protected]";
        $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();

Also, check http://toroweb.org/

分享给朋友:
您可能感兴趣的文章:
随机阅读: