Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ivolovikov committed Oct 15, 2012
1 parent f187e6e commit a131dd9
Show file tree
Hide file tree
Showing 18 changed files with 1,526 additions and 3 deletions.
107 changes: 104 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,105 @@
yii-rest-api
============
## Yii RESTful API

This is extension for Yii Framework (http://www.yiiframework.com/), which can easy add RESTful API to existing web application.

### INSTALLATION

All of this code yo can see in *demo* folder.

- Unpack *library* folder to *YOUR_EXTENSION_PATH/yii-rest-api*
- Update yours *config/main.php*

Add new path of alias at the beginning

YiiBase::setPathOfAlias('rest', realpath(__DIR__ . 'YOUR_EXTENSION_PATH/yii-rest-api/library/rest'));

Add extension service to preload and components sections

'preload' => array('restService'),

'components' => array(
'restService' => array(
'class' => '\rest\Service',
'enable' => isset($_REQUEST['_rest']), // for example
),
),

Change routing settings

'urlManager'=>array(
'urlFormat' => 'path',
'showScriptName' => false,
'baseUrl' => '',
'rules' => array(
array('<controller>/index', 'pattern' => 'api/<controller:\w+>', 'verb' => 'GET'),
array('<controller>/create', 'pattern' => 'api/<controller:\w+>', 'verb' => 'POST'),
array('<controller>/view', 'pattern' => 'api/<controller:\w+>/<id>', 'verb' => 'GET'),
array('<controller>/update', 'pattern' => 'api/<controller:\w+>/<id>', 'verb' => 'PUT'),
array('<controller>/delete', 'pattern' => 'api/<controller:\w+>/<id>', 'verb' => 'DELETE'),
)
),

- Update parent or specific Controller

Add behavior

public function behaviors()
{
return array(
'restAPI' => array('class' => '\rest\controller\Behavior')
);
}

Overwrite render method (if need it)

public function render($view, $data = null, $return = false, array $fields = null)
{
if (($behavior = $this->asa('restAPI')) && $behavior->getEnabled()) {
return $this->renderRest($view, $data, $return, $fields);
} else {
return parent::render($view, $data, $return);
}
}

Overwrite redirect method (if need it)

public function redirect($url, $terminate = true, $statusCode = 302)
{
if (($behavior = $this->asa('restAPI')) && $behavior->getEnabled()) {
$this->redirectRest($url, $terminate, $statusCode);
} else {
parent::redirect($url, $terminate, $statusCode);
}
}

- Upate parent or specific ActiveRecord Model (or any other instance of CModel), if you need render rules.

Add behavior

public function behaviors()
{
return array(
'renderModel' => array('class' => '\rest\model\Behavior')
);
}

Add rule

public function rules()
{
return array(
array('field1,field2,field3', 'safe', 'on' => 'render'),
);
}

### REQUIREMENTS

PHP >= 5.3.0
Yii Framework >= 1.1.8

### LICENSE

Copyright 2012 Pays I/O Ltd.

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

Yii RESTful API
24 changes: 24 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "paysio/yii-rest-api",
"description": "Yii Rest API Service",
"type": "yii-extension",
"keywords": [
"Yii RESTful API",
"REST API"
],
"homepage": "https://github.com/paysio/yii-rest-api",
"license": "MIT",
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "*",
"ext-curl": "*"
},
"autoload": {
"psr-0": {
"rest\\": "library/",
"restTest\\": "tests/"
}
}
}
43 changes: 43 additions & 0 deletions demo/config/main.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
/**
* Yii RESTful API
*
* @link https://github.com/paysio/yii-rest-api
* @copyright Copyright (c) 2012 Pays I/O Ltd. (http://pays.io)
* @license http://www.opensource.org/licenses/mit-license.php MIT license
* @package REST_Service_DEMO
*/

YiiBase::setPathOfAlias('rest', realpath(__DIR__ . '/../extensions/yii-rest-api/library/rest'));

return array(
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
'name' => 'My Web Application',

'preload' => array('restService'),

'import' => array(
'application.models.*',
'application.components.*',
),

'components' => array(
'restService' => array(
'class' => '\rest\Service',
'enable' => isset($_REQUEST['_rest']),
),

'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'baseUrl' => '',
'rules' => array(
array('<controller>/index', 'pattern' => 'api/<controller:\w+>', 'verb' => 'GET'),
array('<controller>/create', 'pattern' => 'api/<controller:\w+>', 'verb' => 'POST'),
array('<controller>/view', 'pattern' => 'api/<controller:\w+>/<id>', 'verb' => 'GET'),
array('<controller>/update', 'pattern' => 'api/<controller:\w+>/<id>', 'verb' => 'PUT'),
array('<controller>/delete', 'pattern' => 'api/<controller:\w+>/<id>', 'verb' => 'DELETE'),
)
),
),
);
147 changes: 147 additions & 0 deletions demo/controllers/RestController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<?php
/**
* Yii RESTful API
*
* @link https://github.com/paysio/yii-rest-api
* @copyright Copyright (c) 2012 Pays I/O Ltd. (http://pays.io)
* @license http://www.opensource.org/licenses/mit-license.php MIT license
* @package REST_Service_DEMO
*/

/**
* @method bool isPost()
* @method bool isPut()
* @method bool isDelete()
* @method string renderRest(string $view, array $data = null, bool $return = false, array $fields = array())
* @method void redirectRest(string $url, bool $terminate = true, int $statusCode = 302)
* @method bool isRestService()
* @method \rest\Service getRestService()
*/
class RestController extends Controller
{
public function init()
{
Yii::app()->restService->enable();
}

/**
* @return array
*/
public function behaviors()
{
return array(
'restAPI' => array('class' => '\rest\controller\Behavior')
);
}

public function actionIndex()
{
$model = new RestMockModel();
$data = array(
'count' => 100,
'data' => array($model, $model, $model)
);
$this->render('empty', $data, false, array('count', 'data'));
}

public function actionView()
{
$model = $this->loadModel();
$this->render('empty', array('model' => $model), false, array('model'));
}

public function actionCreate()
{
$model = new RestMockModel();

if ($this->isPost() && ($data = $_POST)) {
$model->attributes = $data;
if ($model->validate()) {
$this->redirect(array('view', 'id' => $model), true, 201);
}
}
$this->render('empty', array('model' => $model), false, array('model'));
}

public function actionUpdate()
{
$model = $this->loadModel();
$data = array(
'version' => Yii::app()->request->getPut('version'),
'name' => Yii::app()->request->getPut('name'),
);

if ($this->isPut() && $data) {
$model->attributes = $data;
if ($model->validate()) {
$this->redirect(array('view', 'id' => $model));
}
}
$this->render('empty', array('model' => $model), false, array('model'));
}

public function actionDelete()
{
if ($this->isDelete()) {
$model = $this->loadModel();
$this->redirect(array('index', $model));
} else {
throw new \CHttpException(400, Yii::t('app', 'Invalid delete request'));
}
}

/**
* @return RestMockModel
* @throws CHttpException
*/
public function loadModel()
{
$id = isset($_GET['id']) ? $_GET['id'] : null;
$object = new RestMockModel();
if ($id != $object->id) {
throw new CHttpException(404, Yii::t('app', 'Object not found'));
}
return $object;
}



/**
* Renders a view with a layout.
*
* @param string $view name of the view to be rendered. See {@link getViewFile} for details
* about how the view script is resolved.
* @param array $data data to be extracted into PHP variables and made available to the view script
* @param boolean $return whether the rendering result should be returned instead of being displayed to end users.
* @param array $fields allowed fields to REST render
* @return string the rendering result. Null if the rendering result is not required.
* @see renderPartial
* @see getLayoutFile
*/
public function render($view, $data = null, $return = false, array $fields = array())
{
if (($behavior = $this->asa('restAPI')) && $behavior->getEnabled()) {
return $this->renderRest($view, $data, $return, $fields);
} else {
return parent::render($view, $data, $return);
}
}

/**
* Redirects the browser to the specified URL or route (controller/action).
* @param mixed $url the URL to be redirected to. If the parameter is an array,
* the first element must be a route to a controller action and the rest
* are GET parameters in name-value pairs.
* @param boolean|integer $terminate whether to terminate OR REST response status code !!!
* @param integer $statusCode the HTTP status code. Defaults to 302. See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html}
* for details about HTTP status code.
*/
public function redirect($url, $terminate = true, $statusCode = 302)
{
if (($behavior = $this->asa('restAPI')) && $behavior->getEnabled()) {
$this->redirectRest($url, $terminate, $statusCode);
} else {
parent::redirect($url, $terminate, $statusCode);
}
}
}
59 changes: 59 additions & 0 deletions demo/models/RestMockModel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/**
* Yii RESTful API
*
* @link https://github.com/paysio/yii-rest-api
* @copyright Copyright (c) 2012 Pays I/O Ltd. (http://pays.io)
* @license http://www.opensource.org/licenses/mit-license.php MIT license
* @package REST_Service_DEMO
*/

/**
* @method array getRenderAttributes(bool $recursive = true)
*/
class RestMockModel extends CModel
{
public $id = 'TEST_ID';

public $version = 0.1;

public $name = 'Yii REST API';

public $hidden;

public function __construct()
{
$this->attachBehaviors($this->behaviors());
}

/**
* @return array
*/
public function attributeNames()
{
return array('id', 'version', 'name', 'hidden');
}

/**
* @return array
*/
public function rules()
{
return array(
array('version', 'numerical'),
array('name', 'length', 'max' => 244),

array('id,version,name', 'safe', 'on' => 'render'),
);
}

/**
* @return array
*/
public function behaviors()
{
return array(
'renderModel' => array('class' => '\rest\model\Behavior')
);
}
}
Loading

0 comments on commit a131dd9

Please sign in to comment.