Yii RESTful Quick Start
学习 RESTful 快速入门 章节时遇到了严重的问题,摸索了2天才搞明白。
总结了如下经验:小白一定要好好按照教程的步骤来做。
工欲善其事,必先利其器
很多大虾做测试时使用的是chrome的postmam,网络上有很多相关教程,可以自行搜索。我测试时使用的是火狐浏览器的插件RESTED。其实也可以使用教程中提到的curl。
开始实例
创建控制器 app\controllers\UserController
如下:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User'; //问题点在此
}
配置URL规则 修改urlManager
如下:
'components' => [
........
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
//'enableStrictParsing' => true,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['user',]],
],
],
...........
],
配置该规则时,对于新手来说也很郁闷,因为不知道该规则应该添加在什么地方,搜索后知道要添加在config/web.php
中的components
里面,按照教程已经完成了。
真的结束了吗?
快速入门的教程说的很清楚:
假设你想通过 RESTful 风格的 API 来展示用户数据。用户数据被存储在用户DB表, 你已经创建了 yii\db\ActiveRecord 类
app\models\User
来访问该用户数据.
然后呢?我发现,在models目录下已经有了User.php的文件,我就误认为改文件已经创建好,并可用。错误提示如下Call to undefined method app\\models\\User::find()
:
OMG,然后我就各种纠结,开始查看UserController.php继承的类ActiveController,里面是这样的:
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction', //重点在这里
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
..........
];
}
然后又看了IndexAction,如下:
protected function prepareDataProvider()
{
if ($this->prepareDataProvider !== null) {
return call_user_func($this->prepareDataProvider, $this);
}
/* @var $modelClass \yii\db\BaseActiveRecord */
$modelClass = $this->modelClass;
return new ActiveDataProvider([
'query' => $modelClass::find(), //重点在这里
]);
}
结合上面的错误提示和之前做过的database章节的练习,发现了最终的问题,原来models中的User.php并不是我们需要的。我为了简化学习过程,就复用了之前练习的Country.php。修改UserController.php代码如下:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
//public $modelClass = 'app\models\User';
public $modelClass = 'app\models\Country'; //复用之前的Country
}
?>
结果正确了,使用火狐插件RESTED如下:
以上图片也算是今天的成果了。
补充
过程当中还存在一个.htaccess的问题,教程中没有提到,但是我在搜索过程中发现需要添加该文件,就在base/web/
目录下面进行了添加,内容如下:
Options +FollowSymLinks
IndexIgnore */*
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
所以没有遇到与htaccess文件相关的问题,若你使用的是nginx可以参考Yii2 隐藏 index.php的配置。