Extension for the Yii PHP Framework that provides a standard Json Ajax Response.
The Jar extension for Yii Framework sets a standard response for JSON based on the JSend Standard.
- Standard structure for JSON responses.
- Simple model response creation.
- Model support for 1:1 relations via dot notation.
- Support for Yii CDataProviders.
- Send function that correctly sets the Content-type
Type | Description | Required Keys | Optional Keys |
---|---|---|---|
success | All went well, and (usually) some data was returned. | status, data | |
fail | There was a problem with the data submitted, or some pre-condition of the API call wasn't satisfied | status, data | |
error | An error occurred in processing the request, i.e. an exception was thrown | status, message | code, data |
Drop Jar.php into the application.extensions directory.
Example Success Response:
{
status : "success",
data : {
"posts" : [
{ "id" : 1, "title" : "A blog post", "body" : "Some useful content" },
{ "id" : 2, "title" : "Another blog post", "body" : "More content" },
]
}
}
Example Error Response:
{
"status" : "error",
"message" : "A title is required"
}
Note that almost all the methods support chaining.
$attributes
is an array that will strip down the given active record models to only those
parameters. It supports dot notation for 1:1 relations, so Model->relation->variable
can be gotten via
relation.variable and is then placed into an object for that relation.
addData([string Key], Value)
- Add a simple key, value into the data array. Value can be anything that CJSON::encode supports.unsetData([string Key])
- Removes data from the data arrayaddModel(Model, $attributes)
- Adds a model to the array for the model's class.resp.data.Model[0].attribute
addModels(Models[], $attributes)
- Adds an array of models to the array for the model's class.resp.data.Model[]
addDataProvider(CDataProvider, $attributes)
- Handles CActiveRecordDataProvider in the same way asaddModels()
, but other CDataProviders by adding their rows tojavascript resp.data.row[]
- Default success. (Returns: status, data)
fail()
- Things like validation errors. (Returns: status, data)error('An error message string.', [Error Code])
- (Returns: status, message, code(optional), data(optional))reset()
- Resets all the data to nothing and the status to success.
hasSuccess()
- Boolean ReturnhasError()
- Boolean ReturnhasFail()
- Boolean Return
getJson()
- Returns theCJSON::encode()
stringgetData()
- Returns the data array
send()
- Echoes out the Json and ends the Application withYii::app()->end();