I have an application that uses JSON to comunicate the front end with the service.
After a few tests with yii i have an idea, but i don't know if it's the best to offer JSON by the MVC pattern.
Extend CController to a CJsonController and it catch all the action return the JSON Objet to serialize
Override CJsonController::run method to this:
public function run($actionID)
{
echo json_encode(parent::run($actionID));
}
return the object to serialize in the action method.
Another way is to make a widget to transform a parameter to JSON. It will be a little more extensible than this way and the controller remains as the base class.
I don't know which one use or if you know some other way.
Why don't you just call json_encode() in your actions to get the needed JSON responses? Creating a JsonController as you described is fine, but it seems to me complicate things unnecessarily.
Because you are returning some structured data rather than text strings, it is inappropriate to use views here.
Another way to solve your problem (if you still want to avoid calling json_encode explicitly in each action) is that you declare a base action class. In its run() method you do JSON encoding.
class JsonAction extends CAction
{
public function run()
{
echo json_encode($this->runJson());
}
}
class Action1 extends JsonAction
{
protected function runJson()
{
// generate data
// return data
}
}
Have to bring back this rather old topic: Is there an easy way to create a JSON object from a AR query? This doesn't do, what i thought:
<?php
$projects=Project::model()->findAll();
// both give [{"isNewRecord":false},{"isNewRecord":false}]
echo json_encode($projects);
echo CJSON::encode($projects);
I also wondered, what the CJSON::nameValue() method is for and how it's used. It would be nice, if you could specify the AR attributes that i need in my JSON response somehow (i don't want all of them). Is that what nameValue() is for?
I could use CDbCriteria's select property, to only fetch the columns i want in my response. But what about custom attributes again?
<?php
class Customer extends CActiveRecord {
public function getFullName()
{
return $this->firstname.' '.$this->lastname;
}