PHP code example of dogancelik / slim-json

1. Go to this page and download the library: Download dogancelik/slim-json library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dogancelik / slim-json example snippets



$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();

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

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

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

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

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

$app = new \Slim\Slim();

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

$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);

$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()]);
});

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

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