<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\helpers\Json;
use app\models\WhiteBoard;
class ApiwhiteboardController extends Controller{
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
function respondJSONCode($pCode){
$msg = "Unknown Error.";
switch($pCode){
case 400: $msg = "Bad request";break;
case 404: $msg = "The requested element was not found.";break;
case 200: $msg = "Ok.";break;
case 406: $msg = "Not Acceptable.";break;
}
return $this->respondJSON(null,$pCode,$msg);
}
function respondJSON($responseValue=null,$code=200,$msg="Ok"){
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/json');
$responseObject = array('code'=>$code,'value'=>$responseValue);
if($responseValue == null){
$responseObject['msg'] = $msg;
}
return $responseObject;
Yii::$app->end();
}
function actionAll() {
$messages = WhiteBoard::find()->all();
return $this->respondJSON(self::model2Array( $messages ) );
}
/**
*View a single element
*/
public function actionView($id){
$m = WhiteBoard::findOne($id);
if($m == null){
return $this->respondJSONCode(404);
}else{
return $this->respondJSON( self::model2Array( $m ) );
}
}
/**
*Delete element by id
*/
public function actionDelete($id){
$m = WhiteBoard::findOne($id);
if($m == null){
return $this->respondJSONCode(404);
}else{
if($m->delete())
return $this->respondJSON( );
else
return $this->respondJSON( array('action'=>'delete', 'status'=>'error', 'errors'=>$m->errors) );
}
}
/**
*Create element by raw json
*/
public function actionCreate(){
$json = file_get_contents('php://input');
$put_vars = Json::decode($json,true); //true means use associative array
if(empty($put_vars))
{
return $this->respondJSON( array('error'=>'Bad request', 'expected'=>'json raw data'), 400 );
Yii::$app->end();
}
$m = new WhiteBoard;
$m->attributes = $put_vars;
if($m->save())
return $this->respondJSON( array('action'=>'create', 'status'=>'ok', 'attributes'=>$m->attributes) );
else
return $this->respondJSON( array('action'=>'create', 'status'=>'error', 'attributes'=>$m->attributes, 'errors'=>$m->errors) );
}
/**
*Update element by raw json
*TODO: determinar si hace falta retornar los atributos, al menos el ID de la insersion ese si
*/
public function actionUpdate($id){
$json = file_get_contents('php://input');
$put_vars = Json::decode($json,true); //true means use associative array
if(empty($put_vars))
{
return $this->respondJSONCode( 400 );
Yii::$app->end();
}
$m = WhiteBoard::findOne($id);
if($m == null) {
return $this->respondJSONCode( 404 );
Yii::$app->end();
}
$m->attributes = $put_vars;
if($m->save())
return $this->respondJSON( array('action'=>'update', 'status'=>'ok', 'attributes'=>$m->attributes) );
else
return $this->respondJSON( array('action'=>'update', 'status'=>'error', 'attributes'=>$m->attributes, 'errors'=>$m->errors) );
}
//Util func
private static function model2Array($models) {
if (is_array($models))
$arrayMode = TRUE;
else {
$models = array($models);
$arrayMode = FALSE;
}
$result = array();
foreach ($models as $model) {
$attributes = $model->getAttributes();
if ($arrayMode)
array_push($result, $attributes);
else
$result = $attributes;
}
return $result;
}
}
?>
Yii2 API Example, desde cero
Controllador
$config = [
...
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => [
'GET api/whiteboard/'=>'apiwhiteboard/all',
'GET api/whiteboard/<id:\d+>'=>'apiwhiteboard/view',
'DELETE api/whiteboard/<id:\d+>'=>'apiwhiteboard/delete',
'POST api/whiteboard/'=>'apiwhiteboard/create',
'PUT api/whiteboard/<id:\d+>'=>'apiwhiteboard/update',
...
],
],
...
Config Routes
config > web.php
namespace app\controllers;
use yii\rest\ActiveController;
class EasyController extends ActiveController
{
public $modelClass = 'app\models\WhiteBoard';
}
Controller
Route config
...
'urlManager' => [
...
'rules' => [
...
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
...
],
],
...