Nano 是一个非常非常小巧的 PHP 应用,允许您创建非常快速的 REST 接口。

v1.3.1 2020-03-04 16:23 UTC

This package is auto-updated.

Last update: 2024-09-18 06:19:27 UTC


README

nano API

Nano

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

欢迎贡献

Nano 是一个非常非常小巧的 PHP 库,允许您创建非常快速的 REST API。

它就像 Slim,但 Nano 只有 ~6.4 千字节

要求

严格要求 PHP 7.4。

安装

通过 Composer

$ composer require midorikocak/nano

使用

简单实例化并在您的应用程序中包含。

require __DIR__ . '/vendor/autoload.php';

use midorikocak\nano\Api;

$api = new Api();

我知道,它不是静态的。

定义 REST 资源

定义 REST 路由和使用通配符都很简单。

$message = 'Welcome to Nano';

$api->get('/', function () use ($message) {
    echo json_encode(['message' => $message]);
    http_response_code(200);
});

$api->post('/', function () use ($message) {
    $input = (array)json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
    echo json_encode($input);
    http_response_code(201);
});

$api->get('/echo/{$message}', function ($message) {
    echo json_encode(['message' => $message]);
    http_response_code(200);
});

基本认证

可以将您的路由隐藏在认证层后面。目前它期望基本认证,更多方法即将推出。

$authFunction = function ($username, $password) {
    return ($username == 'username' && $password == 'password');
};

$api->auth(function () use (&$api) {

    $api->get('/entries/{id}', function ($id) {
        echo json_encode(['id' => $id]);
        http_response_code(201);
    });

    $api->post('/entries/{id}', function ($id) {
        echo json_encode(['id' => $id]);
        http_response_code(201);
    });

    $api->put('/entries/{id}', function ($id) {
        echo json_encode(['id' => $id]);
        http_response_code(204);
    });

    $api->delete('/entries/{id}', function ($id) {
        http_response_code(204);
    });

}, $authFunction);

因此基本认证不是加密的,强烈建议使用 https。

测试

您可以使用 Guzzle/Client 测试您的实时 API。

<?php

declare(strict_types=1);

namespace midorikocak\nano;

use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;

class IntegrationTest extends TestCase
{
    public function testGet(): void
    {
        $client = new Client(
            [
                'base_uri' => $this->baseUri,
                'http_errors' => false,
            ],
        );

        $response = $client->request('GET', '/echo/hello');
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertStringContainsString('hello', (string)$response->getBody());
    }

动机

主要是教育目的。

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

测试

$ composer test

贡献

有关详细信息,请参阅 CONTRIBUTINGCODE_OF_CONDUCT

安全

如果您发现任何与安全相关的问题,请通过电子邮件 mtkocak@gmail.com 反馈,而不是使用问题跟踪器。

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件