2

我试图通过引用Yii2 REST GUIDE创建一个REST API ,但不幸的是我只有 GET 方法工作。

示例网址:

http://dev.exp-yii.com/employee

除了上面的 URL,其他所有东西都给了我一个NOT FOUND (404)错误页面(甚至不是 JSON 响应)。

app\controllers\EmployeeController.php

<?php

namespace app\controllers;

use yii\rest\ActiveController;

class EmployeeController extends ActiveController
{
    public $modelClass = 'app\models\Employee';

    /**
     * @return array
     */
    protected function verbs()
    {

        return [
            'index' => ['GET', 'HEAD'],
            'view' => ['GET', 'HEAD'],
            'create' => ['POST'],
            'update' => ['PUT', 'PATCH'],
            'delete' => ['DELETE'],
        ];

    }

}

应用\模型\Employee.php

<?php

namespace app\models;

use Yii;


class Employee extends \yii\db\ActiveRecord
{
    public $primaryKey = 'emp_no';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'employees';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['emp_no', 'birth_date', 'first_name', 'last_name', 'gender', 'hire_date'], 'required'],
            [['emp_no'], 'integer'],
            [['birth_date', 'hire_date'], 'safe'],
            [['gender'], 'string'],
            [['first_name'], 'string', 'max' => 14],
            [['last_name'], 'string', 'max' => 16],
            [['emp_no'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'emp_no' => 'Emp No',
            'birth_date' => 'Birth Date',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'gender' => 'Gender',
            'hire_date' => 'Hire Date',
        ];
    }

web.php 配置

'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => 'employer'],
            ],
        ],

.htaccess

RewriteEngine on

# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

我希望我已经提供了所有相关信息来解决我的问题。提前致谢。:-)

4

1 回答 1

5

您已经将控制器的名称定义为如果我没有错的employer话应该是这样,这不是在这里编写代码的错字employee

更改为以下

 ['class' => 'yii\rest\UrlRule', 'controller' => 'employee'],
于 2018-03-18T09:03:12.313 回答