dogancelik/slim-json 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

dogancelik/slim-json

Composer 安装命令:

composer require dogancelik/slim-json

包简介

JSON middleware for Slim PHP framework

README 文档

README

SlimJson is an easy-to-use and advanced JSON middleware for Slim PHP framework. SlimJson helps you write web apps that return JSON output.

How to install

You can install SlimJson with Composer by:

composer require dogancelik/slim-json

or adding this line to your composer.json file:

"dogancelik/slim-json": "dev-master"

How to use

require 'vendor/autoload.php';
$app = new \Slim\Slim();

// Add the middleware globally
$app->add(new \SlimJson\Middleware(array(
  'json.status' => true,
  'json.override_error' => true,
  'json.override_notfound' => true
)));

$app->get('/', function() use ($app) {
  $app->render(200, ['Hello' => 'World']);
});

$app->get('/error', function() use ($app) {
  throw new \Exception('This is an error');
});

$app->run();

If you go to localhost/, you will get: {"Hello": "World", "_status": 200}

If you go to localhost/error: {"error": "This is an error", "_status": 500}

If you go to localhost/notfound: {"error": "'/notfound' is not found.", "_status": 404}

Rendering JSON

If you haven't noticed, I didn't add a JSON view to our Slim app. It's because when you add the middleware, we add the JSON view for you so you don't have to.

You should see that we are using a different $app->render() method here.

Rendering parameters are these: function render(status, data)

  • status is HTTP return code integer or string.
  • data is an array.

Configuration

You can initialize the Middleware with these configuration options.

Example:

$app->add(new \SlimJson\Middleware([
  'json.override_error' => true,
  'json.debug' => true,
  'json.status' => true,
]));

All options are disabled (false) by default. Set them to true to enable.

json.override_error

Configures $app->error to return JSON response with HTTP return code 500. Only works if you add the middleware globally

json.override_notfound

Configures $app->notFound to return JSON response with HTTP return code 404. Only works if you add the middleware globally

json.protect

Adds while(1); to every JSON response. What's this?

json.status

Adds an integer _status field to your JSON response.

json.debug

If you enable this option, SlimJson will add additional debugging info (named as _debug) on error. Exception properties (like message, stacktrace, line, etc.) will be added to JSON response.

json.cors

Enables CORS.

If you set this to true, it will set CORS to * (allow all domains). If you set a string, it will set CORS to that string

json.clear_data

You should read this if you don't use the middleware globally. Read why I added this option.

json.json_encode_options

Passes an $options argument to json_encode.

Visit PHP.net page for available constants for json_encode.

Advanced

Use SlimJson for individual routes

If you don't need JSON for your whole application and want to return JSON for individual routes:

Instead of adding the middleware globally, put $app->add inside the routers you want:

$app->get('/', function() use ($app) {
  $app->add(new \SlimJson\Middleware([
    'json.status' => true
  ]));

  $app->render(200, ['Hello' => 'World']);
});

Use inject() for handiness and happiness 😄

I created a static method under the middleware called inject($app, $config), it is basically same as calling $app->add(); but good for a clean and shorter code. Passing the arguments $app and $config is both optional.

Replace this:

$app->add(new \SlimJson\Middleware([
  'json.status' => true
]));

With this:

\SlimJson\Middleware::inject([
  'json.status' => true
]));

Set your own $app->error or $app->notFound message

If you add the middleware globally and enable json.override_error or json.override_notfound, SlimJson will use its own message format for each handler. But you can change that too!

Using config

$app = new \Slim\Slim();

$app->add(new \SlimJson\Middleware([
  'json.override_notfound' => function($request) {
    return 'We can\'t find this page: ' . $request->getPath();
  },
]));

Using Middleware method

$app = new \Slim\Slim();

$slimjson = new \SlimJson\Middleware();

// use `setNotFoundMessage` for `$app->notFound` message
$slimjson->setErrorMessage(function($exception) {
  return 'Custom error message: ' . $exception->getMessage();
});

$app->add($slimjson);

Edge case option: json.clear_data

Read this option if you don't use the middleware globally. You may encounter this error.

Let's say you have a GET router (/foobar) and an error handler:

$app->get('/foobar', function() use ($app) {
  \SlimJson\Middleware::inject();
  $app->render(200, ['foo' => 'bar']);
});

$app->error(function (\Exception $e) use ($app) {
  \SlimJson\Middleware::inject();
  $app->render(500, ['error' => $e->getMessage()]);
});

What happens if you take out inject() from the GET router? So it would be like this:

$app->get('/foobar', function() use ($app) {
  $app->render(200, ['foo' => 'bar']);
});

Then if you go to /foobar you will get an error like this:

{"foo" => "bar", "error" => "View cannot render 200 because the template does not exist"}

Notice you both have foo and error keys. It's because Slim uses $app->view->appendData().

Why did this happen? Because we forgot to add \SlimJson\Middleware::inject(); to the GET router; So don't forget to add this.

If you enable this option, it will remove all data. It may remove other middlewares' data (like Flash (Session) middleware) but I haven't tested it.

But if you really want to use this then add inject(array('json_clear_data' => true)) to your error handler:

$app->error(function (\Exception $e) use ($app) {
  \SlimJson\Middleware::inject(array(
    'json.clear_data' => true
  ));
  $app->render(500, ['error' => $e->getMessage()]);
});

dogancelik/slim-json 适用场景与选型建议

dogancelik/slim-json 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 88.22k 次下载、GitHub Stars 达 39, 最近一次更新时间为 2014 年 01 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「view」 「middleware」 「slim」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 dogancelik/slim-json 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 dogancelik/slim-json 我们能提供哪些服务?
定制开发 / 二次开发

基于 dogancelik/slim-json 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 88.22k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 41
  • 点击次数: 13
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 39
  • Watchers: 3
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2014-01-22