yii2
安らかなAPI
サーチ…
残りのAPIから始める
私たちは国を含むテーブルを持っていますので、countrylistモデルと呼ばれるモデルを作成します
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "countrylist".
*
* @property integer $id
* @property string $iso
* @property string $name
* @property string $nicename
* @property string $iso3
* @property integer $numcode
* @property integer $phonecode
*/
class Countrylist extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'countrylist';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['iso', 'name', 'nicename', 'phonecode'], 'required'],
[['numcode', 'phonecode'], 'integer'],
[['iso'], 'string', 'max' => 2],
[['name', 'nicename'], 'string', 'max' => 80],
[['iso3'], 'string', 'max' => 3]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'iso' => 'Iso',
'name' => 'Name',
'nicename' => 'Nicename',
'iso3' => 'Iso3',
'numcode' => 'Numcode',
'phonecode' => 'Phonecode',
];
}
}
私はrestapi用のコントローラを作成し、モデルクラスのmodelClass変数を設定します。
<?php
namespace app\controllers;
use yii\rest\ActiveController;
use Yii;
class CountrylistController extends ActiveController
{
public $modelClass='app\models\Countrylist';
}
?>
restapiを使うためにはかなりのURLが必要です
私たちはこのルールをpretty urlに追加します
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
['class'=>'yii\rest\UrlRule','controller'=>'countrylist']
],
],
その後、私たちはアクセスして、残りのAPIをテストすることができます
http:// localhost / countrylistは私達に郡のリストを与えます。
残りのAPIのデフォルトアクションをオーバーライドする方法Yii2
例として、デフォルトのインデックスアクションでページネーションを無効にし、すべての結果をindexで取得したいとします。どうやってそれができる?それは簡単です。コントローラのインデックスアクションを次のようにオーバーライドする必要があります。
public function actions() {
$actions = parent::actions();
unset($actions['index']);
return $actions;
}
public function actionIndex() {
$activeData = new ActiveDataProvider([
'query' => \common\models\Yourmodel::find(),
'pagination' => false
]);
return $activeData;
}
特定のアクションのContent-Typeを上書きする
ユースケース:そのままの状態(テキスト)のコンテンツを返すアクションは1つだけです:
public function actionAsXML()
{
$this->layout = false;
Yii::$app->response->format = Response::FORMAT_XML;
return ['aaa' => [1, 2, 3, 4]];;
}
定義済みの応答形式は次のとおりです。
- FORMAT_HTML
- FORMAT_XML
- FORMAT_JSON
- FORMAT_JSONP
- FORMAT_RAW
text/plain
MIMEタイプはそのままでそのまま使えますが、代わりにこれを使用してください:
public function actionPlainText()
{
$this->layout = false;
Yii::$app->response->format = Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'text/plain');
return $this->render('plain-text'); // outputs template as plain text
}
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow