Developments

Using request of JSON Payload in Slim framework

Slim Framework

How to enable JSON-Payload input in Slim Framework…

SlimMiddlewareContentTypes.php

<?php
/**
 * Middleware SlimMiddlewareContentTypes (for JSON Payload requests)
 * 2015/03/12
 * Aiden Kim
 */
class SlimMiddlewareContentTypes extends \Slim\Middleware\ContentTypes {
	
	public function call() {
		$mediaType = $this->app->request->getMediaType();
		if ( isset($this->contentTypes[$mediaType]) && !$this->app->request->isGet() && !$this->app->request->isHead() ) {
			$env = $this->app->environment();
			// Parse request data
			$form_hash = $this->parse($env['slim.input'], $mediaType);
			if (is_array($form_hash)) {
				// Backup original form-hash
				$env['slim.request.form_hash_original'] = $env['slim.request.form_hash'];
				// Replace new form-hash with parsed Array
				$env['slim.request.form_hash'] = $form_hash;
			}
		}
		$this->next->call();
	}

}
?>

index.asp

<?php
require_once('SlimMiddlewareContentTypes.php');

/**
 * Loading
 */
\Slim\Slim::registerAutoloader();

/**
 * Default conditions
 */
$app = new \Slim\Slim();

/**
 * Route Middleware
 */
$app->add(new SlimMiddlewareContentTypes());

/**
 * Route config
 */
$app->post('/sample', 
	function () use ($app) {
		var_dump($app->request()->params());
		var_dump($app->request()->post());
	}
);
 
/**
 * Run
 */
$app->run();

?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.