Last active
November 1, 2018 13:54
-
-
Save cherifGsoul/3180857 to your computer and use it in GitHub Desktop.
Yii simple rest controller exemple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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->lastname = $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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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/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'), | |
array('contact/delete' , 'pattern'=>'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'=>'[email protected]', | |
), | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Controller is the customized base controller class. | |
* All controller classes for this application should extend from this base class. | |
*/ | |
class RestController 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] : ''; | |
} | |
} |
@dougfelton Thank you
Thanks for the example on returning correct status information. I couldn't find it in the Yii framework documentation. In my opinion, returning the correct status by setting headers is a process in which the framework should play a role.
Nice thx
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very, very much for this. Found a typo: in your config file you have a urlManager rule for 'contact/view' but there's no "view" action in the controller. That rule should read 'contact/show' instead, since the controller action is actually named 'show'