【发布时间】:2018-03-18 06:48:47
【问题描述】:
我尝试通过引用 Yii2 REST GUIDE 创建一个 REST API,但不幸的是我只有 GET 方法可以工作。
示例网址:
除了上面的 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'],
];
}
}
app\models\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
我希望我已经提供了所有相关信息来解决我的问题。提前致谢。 :-)
【问题讨论】:
-
@MuhammadOmerAslam 试过了,没有运气
-
当你的控制器名称是
employee时,为什么你有'controller'=>'employer'? -
@MuhammadOmerAslam,我的糟糕,它现在正在工作。无论如何,谢谢。
-
:) 欢迎您的朋友