Skip to content

Instantly share code, notes, and snippets.

@codev0
Forked from cherifGsoul/RestController.php
Created November 1, 2018 13:54

Revisions

  1. Mohamed Cherif Bouchelaghem revised this gist Jul 22, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -22,7 +22,7 @@ public function actionCreate()

    $model = new Contact();
    if (isset($data['firstname']))
    $model->title = $data['lastname'];
    $model->lastname = $data['lastname'];
    if (isset($data['content']))
    $model->email = $data['email'];

  2. Mohamed Cherif Bouchelaghem revised this gist Jul 22, 2013. 2 changed files with 1 addition and 1 deletion.
    File renamed without changes.
    2 changes: 1 addition & 1 deletion main.php
    Original file line number Diff line number Diff line change
    @@ -41,7 +41,7 @@
    'urlManager'=>array(
    'urlFormat'=>'path',
    'rules'=>array(
    array('contact/view' , 'pattern'=>'contact/<id\d+>' , 'verb'=>'GET'),
    array('contact/show' , 'pattern'=>'contact/<id\d+>' , 'verb'=>'GET'),
    array('contact/list' , 'pattern'=>'contact/' , 'verb'=>'GET'),
    array('contact/create' , 'pattern'=>'contact' , 'verb'=>'POST'),
    array('contact/edit' , 'pattern'=>'contact/<id\d+>' , 'verb'=>'PUT'),
  3. Mohamed Cherif Bouchelaghem revised this gist Jul 26, 2012. 1 changed file with 5 additions and 5 deletions.
    10 changes: 5 additions & 5 deletions main.php
    Original file line number Diff line number Diff line change
    @@ -41,11 +41,11 @@
    'urlManager'=>array(
    'urlFormat'=>'path',
    'rules'=>array(
    array('contact/view' , 'pattern'=>'api/contact/<id\d+>' , 'verb'=>'GET'),
    array('contact/list' , 'pattern'=>'api/contact/' , 'verb'=>'GET'),
    array('contact/create' , 'pattern'=>'api/contact' , 'verb'=>'POST'),
    array('contact/edit' , 'pattern'=>'api/contact/<id\d+>' , 'verb'=>'PUT'),
    array('contact/delete' , 'pattern'=>'api/contact/<id\d+>' , 'verb'=>'DELETE'),
    array('contact/view' , 'pattern'=>'contact/<id\d+>' , 'verb'=>'GET'),
    array('contact/list' , 'pattern'=>'contact/' , 'verb'=>'GET'),
    array('contact/create' , 'pattern'=>'contact' , 'verb'=>'POST'),
    array('contact/edit' , 'pattern'=>'contact/<id\d+>' , 'verb'=>'PUT'),
    array('contact/delete' , 'pattern'=>'contact/<id\d+>' , 'verb'=>'DELETE'),

    /*'<controller:\w+>/<id:\d+>'=>'<controller>/view',
    '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
  4. Mohamed Cherif Bouchelaghem revised this gist Jul 26, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion RestController.php
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@
    * Controller is the customized base controller class.
    * All controller classes for this application should extend from this base class.
    */
    class Controller extends CController
    class RestController extends CController
    {
    /**
    * @var string the default layout for the controller view. Defaults to '//layouts/column1',
  5. Mohamed Cherif Bouchelaghem created this gist Jul 26, 2012.
    97 changes: 97 additions & 0 deletions RestController.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,97 @@
    <?php
    /**
    * Controller is the customized base controller class.
    * All controller classes for this application should extend from this base class.
    */
    class Controller extends CController
    {
    /**
    * @var string the default layout for the controller view. Defaults to '//layouts/column1',
    * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
    */
    public $layout='//layouts/main';
    /**
    * @var array context menu items. This property will be assigned to {@link CMenu::items}.
    */
    public $menu=array();
    /**
    * @var array the breadcrumbs of the current page. The value of this property will
    * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
    * for more details on how to specify this property.
    */
    public $breadcrumbs=array();


    /**
    * Send raw HTTP response
    * @param int $status HTTP status code
    * @param string $body The body of the HTTP response
    * @param string $contentType Header content-type
    * @return HTTP response
    */
    protected function sendResponse($status = 200, $body = '', $contentType = 'application/json')
    {
    // Set the status
    $statusHeader = 'HTTP/1.1 ' . $status . ' ' . $this->getStatusCodeMessage($status);
    header($statusHeader);
    // Set the content type
    header('Content-type: ' . $contentType);

    echo $body;
    Yii::app()->end();
    }

    /**
    * Return the http status message based on integer status code
    * @param int $status HTTP status code
    * @return string status message
    */
    protected function getStatusCodeMessage($status)
    {
    $codes = array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    306 => '(Unused)',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',

    );
    return (isset($codes[$status])) ? $codes[$status] : '';
    }
    }
    91 changes: 91 additions & 0 deletions gistfile1.aw
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,91 @@
    <?php

    class ContactController extends RestController
    {
    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    public function actionShow($id)
    {
    $model= Contact::model()->findByPk($id);
    $this->sendResponse(200,CJSON::encode($model));
    }

    /**
    * Creates a new model.
    * If creation is successful, the browser will be redirected to the 'view' page.
    */
    public function actionCreate()
    {
    $data = CJSON::decode(file_get_contents('php://input'));

    $model = new Contact();
    if (isset($data['firstname']))
    $model->title = $data['lastname'];
    if (isset($data['content']))
    $model->email = $data['email'];

    if (!$model->save()) {
    $errors = array();
    foreach ($model->getErrors() as $e) $errors = array_merge($errors, $e);
    $this->sendResponse(500, implode("<br />", $errors));
    }

    $this->sendResponse(200);
    }

    /**
    * Updates a particular model.
    * If update is successful, the browser will be redirected to the 'view' page.
    * @param integer $id the ID of the model to be updated
    */
    public function actionEdit($id)
    {
    $data = CJSON::decode(file_get_contents('php://input'));

    $model = Contact::model()->findByPk($id);

    $model->firstname = $data['firstname'];
    $model->lastname = $data['lastname'];
    $model->email = $data['email'];

    if (!$model->save()) {
    $errors = array();
    foreach ($model->getErrors() as $e) $errors = array_merge($errors, $e);
    $this->sendResponse(500, implode("<br />", $errors));
    }

    $this->sendResponse(200);
    }

    /**
    * Deletes a particular model.
    * If deletion is successful, the browser will be redirected to the 'admin' page.
    * @param integer $id the ID of the model to be deleted
    */
    public function actionDelete($id)
    {
    $model = Contact::model()->findByPk($id);

    if (!$model->delete() && count($model->getErrors())) {
    $errors = array();
    foreach ($model->getErrors() as $e) {
    $errors = array_merge($errors, $e);
    }
    $this->sendResponse(500, implode("<br />", $errors));
    }

    $this->sendResponse(200);
    }

    /**
    * Lists all models.
    */
    public function actionList()
    {
    $models=Contact::model()->findAll();
    $this->sendResponse(200,CJSON::encode($models));
    }

    }
    97 changes: 97 additions & 0 deletions main.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,97 @@
    <?php

    // uncomment the following to define a path alias
    // Yii::setPathOfAlias('local','path/to/local-folder');

    // This is the main Web application configuration. Any writable
    // CWebApplication properties can be configured here.
    return array(
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'My Web Application',

    // preloading 'log' component
    'preload'=>array('log'),

    // autoloading model and component classes
    'import'=>array(
    'application.models.*',
    'application.components.*',
    ),

    'modules'=>array(
    // uncomment the following to enable the Gii tool

    'gii'=>array(
    'class'=>'system.gii.GiiModule',
    'password'=>'aa',
    // If removed, Gii defaults to localhost only. Edit carefully to taste.
    'ipFilters'=>array('127.0.0.1','::1'),
    ),

    ),

    // application components
    'components'=>array(
    'user'=>array(
    // enable cookie-based authentication
    'allowAutoLogin'=>true,
    ),
    // uncomment the following to enable URLs in path-format

    'urlManager'=>array(
    'urlFormat'=>'path',
    'rules'=>array(
    array('contact/view' , 'pattern'=>'api/contact/<id\d+>' , 'verb'=>'GET'),
    array('contact/list' , 'pattern'=>'api/contact/' , 'verb'=>'GET'),
    array('contact/create' , 'pattern'=>'api/contact' , 'verb'=>'POST'),
    array('contact/edit' , 'pattern'=>'api/contact/<id\d+>' , 'verb'=>'PUT'),
    array('contact/delete' , 'pattern'=>'api/contact/<id\d+>' , 'verb'=>'DELETE'),

    /*'<controller:\w+>/<id:\d+>'=>'<controller>/view',
    '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
    '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',*/
    ),
    ),

    /*'db'=>array(
    'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
    ),*/
    // uncomment the following to use a MySQL database

    'db'=>array(
    'connectionString' => 'mysql:host=localhost;dbname=testdrive',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
    'tablePrefix'=>'tbl_',
    ),

    'errorHandler'=>array(
    // use 'site/error' action to display errors
    'errorAction'=>'site/error',
    ),
    'log'=>array(
    'class'=>'CLogRouter',
    'routes'=>array(
    array(
    'class'=>'CFileLogRoute',
    'levels'=>'error, warning',
    ),
    // uncomment the following to show log messages on web pages

    /*array(
    'class'=>'CWebLogRoute',
    ),*/

    ),
    ),
    ),

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
    // this is used in contact page
    'adminEmail'=>'webmaster@example.com',
    ),
    );