關於yii2 REST api 的問題

來源:互聯網
上載者:User

標籤:

首先,需要在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 的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.