App_Controller_Helper_Params for JSON and XML POSTs

Matthew Weier O’Phinney shares a bit of very use­ful code to inject request params into a Zend Frame­work request object from a JSON or XML POST request.

Below is a plu­gin I use to trans­late JSON or XML raw post request data to request user para­me­ters.
Note that it expects a “Content-Type” header of either “application/json” or “application/xml”. If those are detected, it then does the trans­la­tion and injec­tion.
Once it has, you can then sim­ply access the para­me­ters from your request object like any oth­ers.
I actu­ally use this with dojox.data.JsonRestStore already, so you should be set. :)


class App_Controller_Helper_Params
extends Zend_Controller_Action_Helper_Abstract
{
/**
* @var array Parameters detected in raw content body
*/
protected $_bodyParams = array();

/**
* Do detec­tion of con­tent type, and retrieve para­me­ters from raw body if
* present
*
* @return void
*/
pub­lic func­tion init()
{
$request = $this->getRequest();
$con­tent­Type = $request->getHeader(‘Content-Type’);
$raw­Body = $request->getRawBody();
if (!$raw­Body) {
return;
}
switch (true) {
case (strstr($contentType, ‘application/json’)):
$this->setBodyParams(Zend_Json::decode($rawBody));
break;
case (strstr($contentType, ‘application/xml’)):
$con­fig = new Zend_Config_Xml($rawBody);
$this->setBodyParams($config->toArray());
break;
default:
if ($request->isPut()) {
parse_str($rawBody, $params);
$this->setBodyParams($params);
}
break;
}
}

/**
* Set body params
*
* @param array $params
* @return Scrummer_Controller_Action
*/
pub­lic func­tion setBodyParams(array $params)
{
$this->_bodyParams = $params;
return $this;
}

/**
* Retrieve body para­me­ters
*
* @return array
*/
pub­lic func­tion get­Body­Params()
{
return $this->_bodyParams;
}

/**
* Get body para­me­ter
*
* @param string $name
* @return mixed
*/
pub­lic func­tion getBodyParam($name)
{
if ($this->hasBodyParam($name)) {
return $this->_bodyParams[$name];
}
return null;
}

/**
* Is the given body para­me­ter set?
*
* @param string $name
* @return bool
*/
pub­lic func­tion hasBodyParam($name)
{
if (isset($this->_bodyParams[$name])) {
return true;
}
return false;
}

/**
* Do we have any body para­me­ters?
*
* @return bool
*/
pub­lic func­tion has­Body­Params()
{
if (!empty($this->_bodyParams)) {
return true;
}
return false;
}

/**
* Get sub­mit para­me­ters
*
* @return array
*/
pub­lic func­tion get­Sub­mit­Params()
{
if ($this->hasBodyParams()) {
return $this->getBodyParams();
}
return $this->getRequest()->getPost();
}

pub­lic func­tion direct()
{
return $this->getSubmitParams();
}
}

Tags: , , , ,

Leave a Comment

*

Get Adobe Flash playerPlugin by wpburn.com wordpress themes