一、配置url格式及隐藏index.php
1.1 配置urlManager应用元件
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
注意:一定要配置在components下,否则无效。
1.2 创建.htaccess文件
该文件的位置是位于backend或者frontend的入口文件的同级目录,即web目录下。
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 . /frontend/web/index.php [L]
二、创建restful api模块
目录结构例如:
几个注意点:
1.创建Module.php文件
namespace backend\modules\api;
class Module extends \yii\base\Module
{
public $controllerNamespace = 'backend\modules\api\controllers';
public function init()
{
parent::init();
// custom initialization code goes here
}
}
2.在main.php中加载api模块
'modules' => [
'api' => [
'class' => 'backend\modules\api\Module',
],
],
3.api控制器定义以及访问配置
namespace backend\modules\api\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController{
//不要忘记定义modelClass
public $modelClass = 'common\models\User';
}
//配置(config/main.php)
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['api/user'
]],
],
],
http://xxxxxx/manage/api/users
最后可以使用chrome插件Postman调试是否成功,如图: