URL настроек для REST API в Yii2 - PullRequest
0 голосов
/ 12 марта 2019

Я пытаюсь настроить URL для Restaps

в web.php

'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'company',
        'extraPatterns' => [
            'POST' => 'create', // 'xxxxx' refers to 'actionXxxxx'
            'PUT {id}' => 'update',
            'PATCH {id}' => 'update',
            'DELETE {id}' => 'delete',
            'GET {id}' => 'view',
            'GET ' => 'index',
        ],
    ],
],

В CompanyControler:

public $modelClass='app\models\Company';

/* Declare actions supported by APIs (Added in api/modules/v1/components/controller.php too) */
public function actions(){
    $actions = parent::actions();
    unset($actions['create']);
    unset($actions['update']);
    unset($actions['delete']);
    unset($actions['view']);
    unset($actions['index']);
    return $actions;
}

/* Declare methods supported by APIs */
protected function verbs(){
    return [
        'create' => ['POST'],
        'update' => ['PUT', 'PATCH','POST'],
        'delete' => ['DELETE'],
        'view' => ['GET'],
        'index'=>['GET'],
    ];
}
/**
 * {@inheritdoc}
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['logout'],
            'rules' => [
                [
                    'actions' => ['logout'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

public function actionIndex()
{
  // it work
}

public function actionView($id){
    $items = Company::find()->where(['id',$id])->one();
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return $items;
}

Когда я выполняю GET: /company Я получил ответ от actionIndex, но когда я пытаюсь получить company/10 (где 10 - идентификатор элемента), я получаю ошибку 404.

Как правильно настроить менеджер URL?

1 Ответ

1 голос
/ 12 марта 2019

Возможно, проблема не в настройках менеджера URL, а в условии в вашем действии view. Вам следует заменить:

$items = Company::find()->where(['id',$id])->one();

по

$items = Company::find()->where(['id' => $id])->one();
...