수색…


나머지 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이 필요하고
예쁜 URL에이 규칙을 추가합니다.

'urlManager' => [
   'class' => 'yii\web\UrlManager',
   'enablePrettyUrl' => true,
   'showScriptName' => false,
   'rules' => [
       ['class'=>'yii\rest\UrlRule','controller'=>'countrylist']
       ],
    ],

그 후에 우리는 예제로 나머지 API를 테스트 할 수 있습니다.

http : // localhost / countrylist 는 우리에게 카운티 목록을 제공합니다.

나머지 API Yii2의 기본 동작을 재정의하는 방법

예를 들어 기본 색인 작업에서 페이지 매김을 비활성화하고 모든 결과를 색인으로 가져 오려고합니다. 어떻게 했니? 간단 해. 다음과 같이 컨트롤러에서 인덱스 작업을 재정의해야합니다.

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 무시

사용 사례 :있는 그대로 (텍스트) 콘텐츠를 반환해야하는 하나의 작업 :

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