hypermediabehavior Behavior for generating 'href' attribute of a model

  1. Introduction
  2. Requirements
  3. Usage
  4. Todo
  5. Resources

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
0 0
3 followers
0 downloads
Yii Version: Unknown
License: MIT
Category: Web Service
Developed by: ezekielnoob
Created on: Oct 20, 2013
Last updated: 4 years ago

Related Extensions