Introduction ¶
This behavior simply adds a href attribute to to your model in a nice way it also provide expanding of related models,
Requirements ¶
...requirements of using this extension (e.g. Yii 1.1 or above)...
Usage ¶
i recommend to attach the behavior in the controller level.
//this is a modified version of loadModel from yiiwheels
public function loadModel($class, $id, $criteria = array(), $exceptionOnNull = true)
{
$model = parent::loadModel($class, $id, $criteria, $exceptionOnNull);
//transferring $this into $controller since we cannot use $this in a closure
$controller = $this;
//attach the behavior here
$model->attachBehavior('hyperMedia', new HyperMediaBehavior($this->expand, function($model) use ($controller){
return $controller->createUrl('view', array('model'=>strtolower(get_class($model)),'id'=>$model->id));
}));
$model->objectFormatter = function($model, $attributes){
if(get_class($model) == 'User')
{
unset($attributes['password']);
unset($attributes['activation_key']);
}
return $attributes;
};
return $model->format();
}
......
......
//$model will have all the attributes of the model + the href attribute
$model = $this->loadModel('Customer', $id);
echo json_encode($model);
//**
* this should generate something like this
*{href:"api/v1/user/1",username:"someUser", relatedModel:{href:"api/v1/realtedModel/2"}}
*/
Todo ¶
- attribute selection
- circular reference prevention
- pagination
- a helper class for reading models (adding the proper attributes if it's an array or single model )
Resources ¶
- Github repo
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.