RESTfull API
Om van een model een restfull API te maken, voeg de volgende controller toe:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class ApiController extends ActiveController {
public $modelClass = 'app\models\<Model_Naam>';
}
?>
In de browser krijg je XML terug, test via Postman en je ziet dat je JSON terug krijgt.
Of plaats zelf een controller in
class HiscoresController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
],
'class' => '\yii\filters\Cors',
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST'],
'Access-Control-Request-Headers' => ['*'],
],
],
];
}
public static function allowedDomains()
{
return [
// '*', // star allows all domains
'http://localhost:3000',
'http://test2.example.com',
];
}
public function beforeAction($action)
{
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
public function actionApiPost()
{
Yii::$app->response->format = \yii\web\Response:: FORMAT_JSON;
$hiscore = new Hiscores();
$hiscore->scenario = Hiscores::SCENARIO_CREATE;
$hiscore->attributes = yii::$app->request->post();
if($hiscore->validate()) {
$hiscore->save();
} else {
return array('status'=>false,'data'=>$hiscore->getErrors(), 'post'=>yii::$app->request->post(), 'get'=>yii::$app->request->get() );
}
}
public function actionApiGet() {
$sql = "select id, name, score, datetime, ip from hiscores order by score desc";
$result = Yii::$app->db->createCommand($sql)->queryAll();
return json_encode(['data'=>$result]); // of json_encode([$result);
}
public function actionIndex()
{
... // hieronder de standaard code
...
...