简体   繁体   中英

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.

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

Also, check http://toroweb.org/

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM