標籤:
首先,需要在basic/web/檔案夾下添加一個.htaccess檔案
這樣進入項目就會自動訪問index.php檔案,url就不會錯亂了
<IfModule mod_rewrite.c>Options +FollowSymLinksIndexIgnore */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.php</IfModule>
接下來詳解一下官方文檔裡的東西
首先,建立一個 yii\db\ActiveRecord 類app\models\User來訪問user表
然後,建立一個控制器類 app\controllers\UserController 如下,
<?phpnamespace app\controllers;use yii\rest\ActiveController;class UserController extends ActiveController{ public $modelClass = ‘app\models\User‘;}
Then, modify the configuration about the urlManager component in your application configuration:
‘urlManager‘ => [ ‘enablePrettyUrl‘ => true, ‘enableStrictParsing‘ => true, ‘showScriptName‘ => false, ‘rules‘ => [ [‘class‘ => ‘yii\rest\UrlRule‘, ‘controller‘ => ‘user‘], ],]
// 用於表明urlManager是否啟用URL美化功能,在Yii1.1中稱為path格式URL, // Yii2.0中改稱美化。 // 預設不啟用。但實際使用中,特別是產品環境,一般都會啟用。 public $enablePrettyUrl = false; // 是否啟用嚴格解析,如啟用嚴格解析,要求當前請求應至少匹配1個路由規則, // 否則認為是無效路由。 // 這個選項僅在 enablePrettyUrl 啟用後才有效。 public $enableStrictParsing = false;
// 指定是否在URL在保留入口指令碼 index.php public $showScriptName = true;
改成上述設定後,http://localhost/basic/web/users 可以直接存取api(注意自動幫你加了個s)
現在來詳解一下一個urlManager的配置規則:
‘urlManager‘ => [ ‘enablePrettyUrl‘ => true,//true 開啟美化 ‘enableStrictParsing‘ => true,//true啟用嚴格解析,要求當前請求應至少匹配1個路由規則,不給路由就404,例如http://localhost/basic/web/就會404;false就是自己找index ‘showScriptName‘ => false,//指定是否在URL在保留入口指令碼 index.php ‘rules‘ => [ [‘class‘ => ‘yii\rest\UrlRule‘, ‘controller‘ => ‘user‘, ‘pluralize‘=>true], //true需要訪問users; false需要訪問user,預設是true ], ],
GET /users: 逐頁列出所有使用者
HEAD /users: 顯示使用者列表的概要資訊
POST /users: 建立一個新使用者
GET /users/123: 返回使用者 123 的詳細資料
HEAD /users/123: 顯示使用者 123 的概述資訊
PATCH /users/123 and PUT /users/123: 更新使用者123
DELETE /users/123: 刪除使用者123
OPTIONS /users: 顯示關於末端 /users 支援的動詞
OPTIONS /users/123: 顯示有關末端 /users/123 支援的動詞
關於yii2 REST api 的問題