EJsonBehavior Enhancement

[size="5"]After looking at the comments in the EJsonBehavior extension page and according to my needs, I added the following features to the extension:


  • It includes only relations specified by (with) in the model, which are loaded by Eager Method.

  • It gives you the choice to return an array instead of JSON encoded string that is useful in case of (findAll) query.

This is EJsonBehavior Class:

class EJsonBehavior extends CBehavior{


	private $owner;

	private $relations;


	public function toJSON($encode = true){

	    $this->owner = $this->getOwner();


	    if (is_subclass_of($this->owner,'CActiveRecord')){


	        $attributes     = $this->owner->getAttributes();

	        $this->relations= $this->getRelated();


	        foreach($this->relations as $key => $value)


	            $attributes[$key] = $value; 




	        	return CJSON::encode($attributes);


	        	return $attributes;



	    return false;



	private function getRelated()


		$related = array();


		$obj = null;




		foreach($md->relations as $name=>$relation){			


				$obj = $this->owner->getRelated($name);

				$related[$name] = $obj instanceof CActiveRecord ? $obj->getAttributes() : $obj;




	    return $related;



And this example shows you how to use it in (findAll) context:

$devices = Device::model()->with('position')->findAll();


$json = array();

foreach($devices as $device){

	$json[] = $device->toJSON(false, false);			



header('Content-type: application/json');

echo CJSON::encode($json);