racoon/api

Racoon 是一个基本的 API 框架,旨在使构建简单的 PHP API 变得快速简单。

1.0.20 2016-12-21 15:17 UTC

This package is auto-updated.

Last update: 2024-09-15 07:15:42 UTC


README

Build Status Total Downloads Latest Stable Version Latest Unstable Version License

Racoon 是一个基本的 API 框架,旨在使构建简单的 PHP API 变得快速简单。 查看文档

入门指南

自动加载

Racoon 依赖于 Composer 提供的自动加载。如果您不使用 Composer,则需要设置自己的 PSR 自动加载器或开始使用 Composer。

快速入门

创建一个应用程序,添加一些路由并运行应用程序。

index.php

// Create an instance of Racoon
$app = new Racoon\Api\App();

$router = $app->getRouter();
$router->addRouteFile('/path/to/my_routes.php');

$app->run();

/path/to/my_routes.php

$r->addRoute(['GET', 'POST'], '/users/list', '\\MyApp\\Users@list');

/MyApp/Users.php

namespace MyApp;

class Users extends \Racoon\Api\Controller
{

    public function list()
    {
        $userList = [
            'Tom',
            'John',
            'Jess',
            'Jo',
        ];
        return $userList;
    }

}

路由

Racoon 使用 racoon/router 处理路由。

定义路由存储位置

需要在路由文件中添加路由,该文件应该添加到 Router

$router = $app->getRouter();

$router->addRouteFile('/path/to/some_routes.php');

如果您想将路由存储在多个位置,可以按照以下方式操作。

$router = $app->getRouter();

$router
    ->addRouteFile('/path/to/some_routes.php')
    ->addRouteFile('/path/to/more_routes.php')
    ->addRouteFile('/path/to/even_more_routes.php');

如果您定义了多个路由位置,它们将按照您定义的顺序包含/添加。

设置路由

在已添加到路由器的一个路由文件中,您需要按照以下格式定义您的路由。

$httpRequestMethod = ['GET', 'POST'];
$requestUri = '/users/list';
$handlerString = '\\MyApp\\Users@list';
$r->addRoute($httpRequestMethod, $requestUri, $handlerString);

处理器命名空间

如果您像我一样,所有应用程序控制器都在一个命名空间下,您可以使用以下方法简化您的路由文件。

$r->setHandlerNamespace('\\MyApp\\Controllers');

之前

$r->addRoute('GET', '/asd', '\\MyApp\\Controllers\\Example@one');
$r->addRoute('GET', '/fgh', '\\MyApp\\Controllers\\Example@two');
$r->addRoute('GET', '/jkl', '\\MyApp\\Controllers\\Example@three');

之后

$r->setHandlerNamespace('\\MyApp\\Controllers');
$r->addRoute('GET', '/asd', '\\Example@one');
$r->addRoute('GET', '/fgh', '\\Example@two');
$r->addRoute('GET', '/jkl', '\\Example@three');

HTTP 请求方法

该路由应匹配的 HTTP 请求方法。这可以是任何 HTTP 请求类型,例如 GETPOST

可以是 stringstringarray

请求 URI

该路由应匹配的请求 URI。

您可以用多种方式定义请求 URI。

'/users/list'
'/users/get/{userId}'
'/users/get/{userId:\d+}'

有关更多信息,请参阅 FastRoute 路由文档

此处定义的任何通配符/占位符都将传递到控制器/处理器方法中。

处理器字符串

处理器字符串定义了当当前请求匹配路由时应执行的类和方法。

所需的格式是 \MyApp\Users@list,其中 \MyApp\Users 是包括命名空间在内的完整类名,而 list 是您想要在该类中执行的 method。

控制器

您的控制器应扩展 \Racoon\Api\Controller

请求

当您的 Controller 首次实例化时,它将无法访问 Request 对象,但是您可以创建一个 public function setupRequest(),该函数将在将 Request 添加到 Controller 后直接调用。这将允许您根据存储在 Request 中的任何参数设置您的 Controller

您的响应

您不应该从 Controllerecho 任何内容。相反,您的 method 应该 return 些内容,让 Racoon 处理。

响应格式化程序

Racoon 允许您选择如何格式化响应。默认情况下,将使用 \Racoon\Api\Response\Format\JsonFormatter

您可以使用任何您想要的格式化程序,只要它实现了 \Racoon\Api\Response\Format\FormatterInterface

要使用不同的格式化程序,请按照以下步骤操作,其中 \Racoon\Api\Response\Format\JsonFormatter 是您选择的格式化程序。

$formatter = new \Racoon\Api\Response\Format\JsonFormatter();
$app->setResponseFormatter($formatter);

返回错误

为了轻松地为请求提供错误响应,您只需要抛出一个 \Racoon\Api\Exception

throw new \Racoon\Api\Exception(
    Request $request = null, // Not required, but could be useful at another time.
    $displayAsError = false, // True to provide the $message back in the response. False if the framework shouldn't handle it.
    $message, // Your error message.
    $code = 0, // If this is not 0 and $displayAsError is True, the http response code will be set to this.
    \Exception $previous = null // If this is as a result of a previous Exception you can pass that in here.
);

然而,如果您扩展了 \Racoon\Api\Exception,您可以大大简化事情。为了演示这一点,我们可以看看 \Racoon\Api\AuthenticationException

namespace Racoon\Api\Exception;

use Racoon\Api\Request;

class AuthenticationException extends Exception
{

    public function __construct(Request $request = null, $message, \Exception $previous = null)
    {
        parent::__construct($request, true, $message, 401, $previous);
    }

}

这意味着我们可以这样显示错误。

throw new \Racoon\Api\AuthenticationException(null, 'Missing API Key.');

身份验证

默认情况下,Racoon 不会对进入您应用程序的任何请求进行身份验证,但它可以轻松设置。

您可以通过在运行应用程序之前设置一个新的 Authenticator 来覆盖身份验证方法。

$authenticator = new \Racoon\Api\Auth\ApiKeyAuthenticator();
$app->setAuthenticator($authenticator);

可用的身份验证器

NoAuthenticator

这个 Authenticator 允许任何请求通过,因为它不进行任何身份验证。

$authenticator = new \Racoon\Api\Auth\NoAuthenticator();
$app->setAuthenticator($authenticator);

ApiKeyAuthenticator

这个 Authenticator 允许您指定一个包含有效 API 密钥的数组,它将认为这些密钥是有效的。

$authenticator = new \Racoon\Api\Auth\ApiKeyAuthenticator();
$authenticator->setApiKeyName('api_key'); // Tells it to look under api_key to find the api key.
$authenticator->addValidApiKey('dsdasdasdasd'); // Add a valid API key.
$app->setAuthenticator($authenticator);

创建自定义身份验证器

您可以创建自己的 Authenticator,只需确保它实现了 \Racoon\Api\Auth\AuthInterface

架构

您有创建 Schema 的能力,以轻松验证传入的请求,并在用户尝试 API 请求时提供一些基本文档。

Schema 由一个或多个 Item 组成,如果所有项都通过其约束,则将是 valid

以下代码应在 Controller 中运行,并将设置并验证 Schema。用户名需要是 2 到 20 个字符之间的字符串,密码需要是至少有 6 个字符的字符串。

use Racoon\Api\Schema\Schema;
use Racoon\Api\Schema\Translator;

$schema = Schema::create([
    Translator::item('username')->isString(2, 20)->returnItem(),
    Translator::item('password')->isString(6)->returnItem(),
]);

$this->validateSchema($schema);

您可以通过以下方式构建更健壮的规则... 用户名必须是 2 到 4 个字符的字符串,或者 10 到 12 个字符之间的字符串。

use Racoon\Api\Schema\Schema;
use Racoon\Api\Schema\Translator;

$schema = Schema::create([
    Translator::item('username')->isString(2, 4)->alt()->isString(10, 12)->returnItem(),
]);

$this->validateSchema($schema);

验证使用 TomWright/Validator 进行,有关更多信息,请参阅相关的 GitHub 页面

请求

Request 对象包含有关当前请求的大部分信息,例如请求 URI、请求中提供的数据以及当前 Schema。您还可以通过 $this->getRequest()Controller 中访问 Request 对象。

如果您想扩展 Racoon 的功能以存储有关 Request 的更多数据,可以扩展 \Racoon\Api\Request,然后告诉 Racoon 使用您的 Request 类。

namespace MyApp;

class Request extends \Racoon\Api\Request
{
}

$app->setRequestClass('\\MyApp\\Request');

获取请求数据

您可以使用 $request->getRequestData() 获取输入数据,但在 Controller 中还有两个辅助方法可以稍微简化一些事情。

// Fetches the username from the input data, and if it doesn't exist it will return 'unknown'.
$request->getOptionalRequestData('username', 'unknown');

// Fetches the username from the input data.
// If it doesn't exist or has a length of 0, an error message will be shown to the client.
$request->getRequiredRequestData('username');

使用 API

使用 API 简单。

所有数据都以 JSON 格式传递给 Racoon,名为 jsonGETPOST 变量。

如果您想以不同于 json 的名称发送数据,可以这样做。

$app->setJsonKeyName('new_json_key');

假设我们已经为 mydomain.com 设置了东西,并且我们有一个与 /users/get 匹配的路由,该路由需要一个名为 user_id 的必需项。如果我们进行一个 GET 请求,请求看起来应该像这样....

http://mydomain.com/users/get?json={"request":{"user_id": 5}}

请注意,requestjson 中是一个独立的对象。这允许您将身份验证/测试参数与您在 Controller 中实际使用的数据分开。

例如。

http://mydomain.com/users/get?json={"api_key": "easSdasesfWasd","request":{"user_id": 5}}

响应

当与 Racoon 一起工作时,您总是会得到一个格式化的响应,如下所示(取决于您使用的哪个响应格式化器)。

{
    "success": false,
    "message": "Missing required field: asd",
    "schema": {
        "first_name": "first_name must be a string, be at least 3 characters in length."
    },
    "received": {
        "api_key": "qweqwe",
        "request": {
            "first_name": "Tom"
        }
    },
    "time_elapsed": "110.129",
    "response": null
}

成功

如果没有抛出异常,则为 True。如果抛出了异常,则为 False。

消息

控制器设置的消息,或异常消息。

架构

控制器中设置的模式。

接收

发送到API的数据。

耗时

API请求处理所需的时间(以毫秒为单位)。

响应

控制器返回的数据。

HTTP响应码

除了上述内容外,如果抛出设置了返回错误的Exception,将使用该Exceptioncode来设置HTTP响应码。