entomb/slim-json-api

Slim 扩展,用于实现快速 JSON API

1.2.3 2016-06-13 18:16 UTC

This package is not auto-updated.

Last update: 2024-09-23 13:22:07 UTC


README

Latest Stable Version Total Downloads

这是一个 SLIM 框架(https://github.com/codeguy/Slim)的扩展,用于轻松实现 json API。

安装

使用 composer,您可以在 composer.json 中添加以下内容

    {
        "require": {
            "slim/slim": "2.3.*",
            "entomb/slim-json-api": "dev-master"
        }
    }

使用方法

要包含中间件和视图,您只需使用默认的 Slim 方式加载它们。有关 Slim 的更多信息,请参阅这里(https://github.com/codeguy/Slim#getting-started

    require 'vendor/autoload.php';

    $app = new \Slim\Slim();

    $app->view(new \JsonApiView());
    $app->add(new \JsonApiMiddleware());

.htaccess 示例

以下是一个简单的 RESTful API 的 .htaccess 示例

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

示例方法

所有请求都将返回 JSON 输出。使用方法为 $app->render( (int)$HTTP_CODE, (array)$DATA);

示例代码

    $app->get('/', function() use ($app) {
        $app->render(200,array(
                'msg' => 'welcome to my API!',
            ));
    });

示例输出

{
    "msg":"welcome to my API!",
    "error":false,
    "status":200
}

错误

要显示错误,只需在数据数组中将 error => true 设置为 true。所有请求都将有一个 error 参数,默认值为 false。

    $app->get('/user/:id', function($id) use ($app) {

        //your code here

        $app->render(404,array(
                'error' => TRUE,
                'msg'   => 'user not found',
            ));
    });
{
    "msg":"user not found",
    "error":true,
    "status":404
}

您可以选择抛出异常,中间件将捕获所有异常并显示错误消息。

    $app->get('/user/:id', function($id) use ($app) {

        //your code here

        if(...){
            throw new Exception("Something wrong with your request!");
        }
    });
{
    "error": true,
    "msg": "ERROR: Something wrong with your request!",
    "status": 500
}

将响应数据和元数据嵌入到不同的容器中

可以将响应元数据和业务信息分别存储在不同的容器中。

为了实现这一点,只需使用容器名称初始化 JsonApiView

   require 'vendor/autoload.php';

    $app = new \Slim\Slim();

    $app->view(new \JsonApiView("data", "meta"));
    $app->add(new \JsonApiMiddleware());

响应

{
    "data":{
        "msg":"welcome to my API!"
    },
    "meta":{
        "error":false,
        "status":200
    }
}

将特定请求路由到 API

如果您的网站使用常规 HTML 响应,并且只想在特定路由上公开 API 点,则可以使用 Slim 路由中间件定义此功能。

    function APIrequest(){
        $app = \Slim\Slim::getInstance();
        $app->view(new \JsonApiView());
        $app->add(new \JsonApiMiddleware());
    }


    $app->get('/home',function() use($app){
        //regular html response
        $app->render("template.tpl");
    });

    $app->get('/api','APIrequest',function() use($app){
        //this request will have full json responses

        $app->render(200,array(
                'msg' => 'welcome to my API!',
            ));
    });

中间件

中间件将为默认请求设置一些静态路由。 如果您不想使用它,可以将其内容代码复制到您的引导文件中。

重要:请记住使用 $app->config('debug', false);,否则错误仍会打印在 HTML 中