如何在RestFul API中调用特定方法?

时间:2016-02-14 15:53:03

标签: php

我创建了这段代码:

header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

switch ($method) 
{
  case 'PUT':
    break;
  case 'POST':
    do_something_with_post($request);  
    break;
  case 'GET':
    do_something_with_get($request);  
    break;
  case 'DELETE':
    do_something_with_delete($request);  
    break;
  default:
    handle_error($request);  
    break;
}

现在假设我执行了这个命令:

curl -X GET http://localhost/api/method/1

所以switch解雇了GET案例,如何调用函数method并传递参数1? 我应该如何在交换机上配置代码?有人可以帮我解决一下吗?

2 个答案:

答案 0 :(得分:2)

这是将请求路径路由到类的简化方法。此示例假定您的基本路径为/app,并且您有一个名为/classes的子文件夹。类名和文件名必须匹配才能生效。

示例请求:

curl -X POST http://localhost/api/user/123

示例路线:

File....: /app/classes/api/User.php
Class...: new User()
Action..: postAction( $arg1 = 123 )

...

// default route
$base  = rtrim( str_replace( '\\', '/', __DIR__.'/app' ), '/' );
$area  = 'api';   // area (/api, /test, etc.)
$class = 'home';  // class name (Home.php -> new Home(), etc.)

// parse request
$verb  = strtolower( @$_SERVER['REQUEST_METHOD'] );
$path  = parse_url( @$_SERVER['REQUEST_URI'], PHP_URL_PATH );
$args  = explode( '/', trim( $path, '/' ) );

// extract area/class from request path
if( count( $args ) )
{
    $area = array_shift( $args );
}
if( count( $args ) )
{
    $class = array_shift( $args );
}

// finalize class name and file path 
$class  = str_replace( ' ', '', ucwords( str_replace( '-', ' ', $class ) ) );
$file   = $base .'/classes/'. $area .'/'. $class.'.php';
$output = null;

// load/execute class
if( is_file( $file ) )
{
    include_once( $file );

    if( class_exists( $class ) )
    {
        $callable = [ new $class(), $verb.'Action' ];

        if( is_callable( $callable ) )
        {
            $output = call_user_func_array( $callable, $args );
        }
    }
}

// send response output...
if( is_null( $output ) === false )
{
    // ...
}
else
{
    // handle error 
}
exit;

答案 1 :(得分:1)

您需要解析URI:

$pieces = explode('?', $_SERVER['REQUEST_URI']);
$endpoint = $pieces[0];
$endpoint_parts = explode('/', $endpoint);
$api_method = $endpoint_parts[2];
$param = $endpoint_parts[3];

然后你可以用你的URL调用method,如下所示:

$api_method($param);