PHPackages                             dogancelik/slim-json - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. dogancelik/slim-json

ActiveLibrary[Templating &amp; Views](/categories/templating)

dogancelik/slim-json
====================

JSON middleware for Slim PHP framework

v0.4.0(10y ago)3984.0k↓37.5%4[1 issues](https://github.com/dogancelik/slim-json/issues)3MITPHPPHP &gt;=5.3.0

Since Jan 22Pushed 8y ago3 watchersCompare

[ Source](https://github.com/dogancelik/slim-json)[ Packagist](https://packagist.org/packages/dogancelik/slim-json)[ Docs](http://github.com/dogancelik/slim-json)[ RSS](/packages/dogancelik-slim-json/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)DependenciesVersions (7)Used By (3)

SlimJson [![Latest Stable Version](https://camo.githubusercontent.com/2183f8ded4c7aacede803a03dde2aaa0b584c6e43ab2fb1a5fa329fb3d0c343b/68747470733a2f2f706f7365722e707567782e6f72672f646f67616e63656c696b2f736c696d2d6a736f6e2f762f737461626c652e706e67)](https://packagist.org/packages/dogancelik/slim-json)
==============================================================================================================================================================================================================================================================================================================

[](#slimjson-)

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
--------------

[](#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
----------

[](#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

[](#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
-------------

[](#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

[](#jsonoverride_error)

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

### json.override\_notfound

[](#jsonoverride_notfound)

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

### json.protect

[](#jsonprotect)

Adds `while(1);` to every JSON response. [What's this?](http://stackoverflow.com/questions/2669690)

### json.status

[](#jsonstatus)

Adds an integer `_status` field to your JSON response.

### json.debug

[](#jsondebug)

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

[](#jsoncors)

Enables [CORS](http://enable-cors.org/).

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

[](#jsonclear_data)

**[You should read this if you don't use the middleware globally. Read why I added this option.](#slimjson-cleardata)**

### json.json\_encode\_options

[](#jsonjson_encode_options)

Passes an `$options` argument to `json_encode`.

[Visit PHP.net page for available constants for json\_encode.](http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-parameters)

Advanced
--------

[](#advanced)

### Use SlimJson for individual routes

[](#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 😄

[](#use-inject-for-handiness-and-happiness-smile)

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

[](#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

[](#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

[](#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
----------------------------------

[](#edge-case-option-jsonclear_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()]);
});
```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity42

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~120 days

Total

6

Last Release

3898d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/486818?v=4)[Doğan Çelik](/maintainers/dogancelik)[@dogancelik](https://github.com/dogancelik)

---

Top Contributors

[![dogancelik](https://avatars.githubusercontent.com/u/486818?v=4)](https://github.com/dogancelik "dogancelik (15 commits)")[![jwellner](https://avatars.githubusercontent.com/u/224667?v=4)](https://github.com/jwellner "jwellner (3 commits)")[![jeroendelau](https://avatars.githubusercontent.com/u/5286898?v=4)](https://github.com/jeroendelau "jeroendelau (1 commits)")[![pdelre](https://avatars.githubusercontent.com/u/1379248?v=4)](https://github.com/pdelre "pdelre (1 commits)")

---

Tags

jsonmiddlewareslimview

### Embed Badge

![Health badge](/badges/dogancelik-slim-json/health.svg)

```
[![Health](https://phpackages.com/badges/dogancelik-slim-json/health.svg)](https://phpackages.com/packages/dogancelik-slim-json)
```

###  Alternatives

[entomb/slim-json-api

Slim extension to implement fast JSON API's

268156.4k4](/packages/entomb-slim-json-api)[laminas/laminas-view

Fast and type safe HTML templating library with a flexible plugin system supporting multistep template composition

7526.3M230](/packages/laminas-laminas-view)[shoot/shoot

Shoot aims to make providing data to your templates more manageable

40229.9k2](/packages/shoot-shoot)[petebrowne/slim-layout-view

A Custom View supporting Layouts for the Slim Framework.

3518.0k](/packages/petebrowne-slim-layout-view)[davidepastore/slim-config

A slim middleware to read configuration from different files based on hassankhan/config

338.9k1](/packages/davidepastore-slim-config)[scrumptious/slagger

Slim middleware for generating Swagger json for use with Swagger UI

101.2k](/packages/scrumptious-slagger)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
