yii2寫api接口步驟
Yii2如何實現(xiàn)RESTful風(fēng)格的API(推薦:《YII教程》?)
1、建立單獨的應(yīng)用程序
為了增加程序的可維護性,易操作性,我們選擇新建一套應(yīng)用程序,這也是為了和前臺應(yīng)用、后臺應(yīng)用區(qū)分開操作。
在WEB前端(frontend)和后端(backend)的同級目錄,新建一個文件夾,命名api,其目錄結(jié)構(gòu)如下所示:
├─assets │ AppAsset.php ├─config │ bootstrap.php │ main-local.php │ main.php │ params-local.php │ params.php ├─runtime └─web │ index.php ├─assets └─css
可以看出其目錄結(jié)構(gòu)基本上同backend沒有其他差異,因為我們就是拷貝backend項目,只是做了部分優(yōu)化。
友情提醒,該步驟完成以后,需要修改common\config\bootstrap.php文件,對新建的應(yīng)用增加alias別名
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
2、為新建的api應(yīng)用程序美化路由
首先保證你的web服務(wù)器開啟rewrite規(guī)則,細(xì)節(jié)我們就不說了,不過這是前提。
接著配置api/config/main.php文件
'components' => [ // other config 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'enableStrictParsing' =>true, 'rules' => [], ] ],
開啟nginx的rewrite,注意在你的配置文件中加入紅色的文字:
server { charset utf-8; client_max_body_size 128M; listen 80; ## listen for ipv4 #listen [::]:80 default_server ipv6only=on; ## listen for ipv6 server_name mysite.local; root /path/to/basic/web; index index.php; access_log /path/to/basic/log/access.log; error_log /path/to/basic/log/error.log; location / { # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; } # uncomment to avoid processing of calls to non-existing static files by Yii #location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ { # try_files $uri =404; #} #error_page 404 /404.html; # deny accessing php files for the /assets directory location ~ ^/assets/.*\.php$ { deny all; } location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/var/run/php5-fpm.sock; try_files $uri =404; } location ~* /\. { deny all; } }
最后只需要在應(yīng)用入口同級增加.htaccess文件就好,我們以nginx為例
# use mod_rewrite for pretty URL support RewriteEngine on # if a directory or a file exists, use the request directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # otherwise forward the request to index.php RewriteRule . index.php
3、利用gii生成測試modules
用了便于演示說明,我們新建一張數(shù)據(jù)表goods表,并向其中插入幾條數(shù)據(jù)。
CREATE TABLE `goods` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `goods` VALUES ('1', '11111'); INSERT INTO `goods` VALUES ('2', '22222'); INSERT INTO `goods` VALUES ('3', '333'); INSERT INTO `goods` VALUES ('4', '444'); INSERT INTO `goods` VALUES ('5', '555');
接著我們先利用gii生成modules后,再利用gii模塊,按照下圖中生成goods信息
現(xiàn)在,我們的api目錄結(jié)構(gòu)應(yīng)該多個下面這幾個目錄
│ ├─models │ Goods.php │ ├─modules │ └─v1 │ │ Module.php │ │ │ ├─controllers │ │ DefaultController.php │ │ GoodsController.php │ │ │ └─views │ └─default │ index.php
需要說明的是:在生成modules的步驟中,為了使我們的模塊可以訪問,不要忘記在main.php配置文件中添加下面的代碼
<?php ...... 'modules' => [ 'v1' => [ 'class' => 'api\modules\v1\Module', ], ], ......
4、重新配置控制器
為了實現(xiàn)restful風(fēng)格的api,在yii2中,我們需要對控制器進行一下改寫
<?php namespace api\modules\v1\controllers; use yii\rest\ActiveController; class GoodsController extends ActiveController { public $modelClass = 'api\models\Goods'; }
5、為Goods配置Url規(guī)則
'rules' => [ [ 'class' => 'yii\rest\UrlRule', 'controller' => ['v1/goods'] ], ]
6、模擬請求操作
經(jīng)過上面幾個步驟,到此我們已經(jīng)為goods成功創(chuàng)建了滿足restful風(fēng)格的api了。為了更好更方便的演示,我們借助工具postman進行模擬請求。
為了見證一下我們的操作,我們用postman請求一下GET /v1/goods看看結(jié)果如何:
接著我們先利用gii生成modules后,再利用gii模塊,按照下圖中生成goods信息
現(xiàn)在,我們的api目錄結(jié)構(gòu)應(yīng)該多個下面這幾個目錄
從上面截圖中可以清楚的看到,GET /v1/goods 已經(jīng)能夠很方便的獲取我們表中的數(shù)據(jù)了。
當(dāng)然,yii2還對該api封裝了如下操作:
GET /users: 逐頁列出所有用戶 HEAD /users: 顯示用戶列表的概要信息 POST /users: 創(chuàng)建一個新用戶 GET /users/123: 返回用戶 123 的詳細(xì)信息 HEAD /users/123: 顯示用戶 123 的概述信息 PATCH /users/123 and PUT /users/123: 更新用戶123 DELETE /users/123: 刪除用戶123 OPTIONS /users: 顯示關(guān)于末端 /users 支持的動詞 OPTIONS /users/123: 顯示有關(guān)末端 /users/123 支持的動詞
不信的話我們可以利用postman發(fā)送一個post請求到/v1/goods,我們會發(fā)現(xiàn)成功創(chuàng)建了一個新的商品。
需要提醒的是,操作中還請細(xì)心且注意:如果你的控制器末端不是復(fù)數(shù)(比如是blog非blogs)請保證請求的時候是復(fù)數(shù)!這是因為在RESTful架構(gòu)中,網(wǎng)址中只能有名詞而不能包含動詞,名詞又往往與數(shù)據(jù)表相對應(yīng),數(shù)據(jù)表呢又是一個“集合”,因此該名詞往往是復(fù)數(shù)的形式。
7、關(guān)于授權(quán)認(rèn)證
為什么需要授權(quán)認(rèn)證?這在一般的操作中是需要的。比如說用戶要設(shè)置自己的信息。
為了對yii2 restful授權(quán)認(rèn)證說的更清楚,我們將會以兩個兩種不同的方法進行說明。
首先需要開啟認(rèn)證:
假設(shè)我們已經(jīng)按照第3步創(chuàng)建了包含字段access-token的數(shù)據(jù)表user,而且利用gii上生成了相應(yīng)的model和controller
配置main.php文件
'components' => [ 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, 'enableSession'=>false ], ],
為控制器配置authenticator行為指定認(rèn)證方式
<?php namespace api\modules\v1\controllers; use yii\rest\ActiveController; use yii\helpers\ArrayHelper; use yii\filters\auth\QueryParamAuth; class UserController extends ActiveController { public $modelClass = 'api\models\User'; public function behaviors() { return ArrayHelper::merge (parent::behaviors(), [ 'authenticator' => [ 'class' => QueryParamAuth::className() ] ] ); } }
最后我們還需要在identityClass中實現(xiàn)findIdentityByAccessToken方法
public static function findIdentityByAccessToken($token, $type = null) { return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]); }
如此一來,我們先通過postman模擬不帶access-token請求看結(jié)果
{ "name": "Unauthorized", "message": "You are requesting with an invalid credential.", "code": 0, "status": 401, "type": "yii\\web\\UnauthorizedHttpException" }
提示401 我們沒有權(quán)限訪問!
我們在請求的鏈接上攜帶正確的access-token,認(rèn)證通過后,控制器會再繼續(xù)執(zhí)行其他檢查(頻率限制、操作權(quán)限等),才可以返回正確的用戶信息。
需要提醒的是:通過url的形式對access-token傳遞存在一定的風(fēng)險,有可能會造成數(shù)據(jù)的泄漏!一般而言,access-token需要放到HTTP頭中進行傳遞!除非客戶端的請求是jsonp格式的!
關(guān)于授權(quán)認(rèn)證,我們有一篇更詳細(xì)的文章,包括一套完整案例、服務(wù)端返回的數(shù)據(jù)類型定義、自定義錯誤機制等。
8、速率限制
速率限制,該操作完全也是出于安全考慮,我們需要限制同一接口某時間段過多的請求。
速率限制默認(rèn)不啟用,用啟用速率限制,yii\web\User::identityClass 應(yīng)該實現(xiàn)yii\filters\RateLimitInterface,也就是說我們的common\models\User.php需要實現(xiàn)yii\filters\RateLimitInterface接口的三個方法,具體代碼可參考:
use yii\filters\RateLimitInterface; use yii\web\IdentityInterface; class User extends ActiveRecord implements IdentityInterface, RateLimitInterface { // other code ...... // 返回某一時間允許請求的最大數(shù)量,比如設(shè)置10秒內(nèi)最多5次請求(小數(shù)量方便我們模擬測試) public function getRateLimit($request, $action){ return [5, 10]; } // 回剩余的允許的請求和相應(yīng)的UNIX時間戳數(shù) 當(dāng)最后一次速率限制檢查時 public function loadAllowance($request, $action){ return [$this->allowance, $this->allowance_updated_at]; } // 保存允許剩余的請求數(shù)和當(dāng)前的UNIX時間戳 public function saveAllowance($request, $action, $allowance, $timestamp){ $this->allowance = $allowance; $this->allowance_updated_at = $timestamp; $this->save(); } }
需要注意的是,你仍然需要在數(shù)據(jù)表User中新增加兩個字段
allowance:剩余的允許的請求數(shù)量
allowance_updated_at:相應(yīng)的UNIX時間戳數(shù)
在我們啟用了速率限制后,Yii 會自動使用 yii\filters\RateLimiter 為 yii\rest\Controller 配置一個行為過濾器來執(zhí)行速率限制檢查。
現(xiàn)在我們通過postman請求v1/users再看看結(jié)果,會發(fā)現(xiàn)在10秒內(nèi)調(diào)用超過5次API接口,我們會得到狀態(tài)為429太多請求的異常信息。
{ "name": "Too Many Requests", "message": "Rate limit exceeded.", "code": 0, "status": 429, "type": "yii\\web\\TooManyRequestsHttpException" }
9、關(guān)于版本
為了兼容歷史版本而且考慮向后兼容性,我們在一開始操作的時候就以URL的方式實現(xiàn)了版本話,這里就不再進行闡述了。
10、錯誤處理
Yii的REST框架的HTTP狀態(tài)代碼可參考如下就好,沒啥好說的
200: OK。一切正常。
201: 響應(yīng) POST 請求時成功創(chuàng)建一個資源。Location header 包含的URL指向新創(chuàng)建的資源。
204: 該請求被成功處理,響應(yīng)不包含正文內(nèi)容 (類似 DELETE 請求)。
304: 資源沒有被修改??梢允褂镁彺娴陌姹尽?/p>
400: 錯誤的請求??赡芡ㄟ^用戶方面的多種原因引起的,例如在請求體內(nèi)有無效的JSON 數(shù)據(jù),無效的操作參數(shù),等等。
401: 驗證失敗。
403: 已經(jīng)經(jīng)過身份驗證的用戶不允許訪問指定的 API 末端。
404: 所請求的資源不存在。
405: 不被允許的方法。 請檢查 Allow header 允許的HTTP方法。
415: 不支持的媒體類型。 所請求的內(nèi)容類型或版本號是無效的。
422: 數(shù)據(jù)驗證失敗 (例如,響應(yīng)一個 POST 請求)。 請檢查響應(yīng)體內(nèi)詳細(xì)的錯誤消息。
429: 請求過多。 由于限速請求被拒絕。
500: 內(nèi)部服務(wù)器錯誤。 這可能是由于內(nèi)部程序錯誤引起的。
Atas ialah kandungan terperinci yii2寫api接口步驟. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Alat AI Hot

Undress AI Tool
Gambar buka pakaian secara percuma

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

No,MVCisnotnecessarilythebestarchitectureanymore,butitremainsrelevant.1)MVC'ssimplicityandseparationofconcernsarebeneficialforsmallerapplications.2)Forcomplexapplications,alternativeslikeMVVMandmicroservicesofferbetterscalabilityandmaintainability.

Yiiisspecialduetoitshighperformance, robustsecurity, kuatcaching, giicodegenerator, modulararchitecture, andefficientcomponent-berasaskan-berasaskan.1) HighperformanceAndSecurityFeatureSenHanceapplicationFiencySafety.2) CachingsymemprovesProveStoFroveShineShiency.2) CachingsymemprovesProvesProveShipShiShiency.2) CachingsymemprovesProvesProvesProves

ToConfigureayiiwidget, yoCallitwithaconfigurationArrayThatsetSetSpropertiesandOptions.1.usethesyntax \\ yii \\ widgets \\ classname :: w idget ($ config) inyourview.2.definethe $ configArrayWithKeysMatchingTheWidget'sPublicProperties.3.SomewidgetSSupportNestedArraySf

MvcinlaravelisadesignpatternThatseparatesapplicationLogicintothreecomponents: model, view, andcontroller.1) Modelshandledataandbusinesslogic, usingeloquentormforforfientdatamanagement.2)

Untuk memasang rangka kerja YII, anda perlu mengkonfigurasi PHP dan komposer mengikut sistem operasi yang berbeza. Langkah-langkah khusus adalah seperti berikut: 1. 2. Adalah disyorkan untuk menggunakan homebrew untuk memasang PHP dan komposer, kemudian membuat projek dan memulakan pelayan pembangunan; 3. Linux (seperti Ubuntu) memasang PHP, sambungan dan komposer melalui APT, kemudian membuat projek dan menggunakan persekitaran formal dengan Apache atau Nginx. Perbezaan utama antara sistem yang berbeza adalah dalam peringkat pembinaan persekitaran. Sebaik sahaja PHP dan komposer siap, proses seterusnya adalah konsisten. Nota

Yiiframeworkexcelsduetoitsspeed, keselamatan, danscalability.1) itoffersHighperformanceWithlazyloadingandcaching.2) robustsecurityfeaturesincludecsrfprotecticeandsecuresessionManagement.3)

Adalah penting untuk memaparkan ralat pengesahan dengan jelas apabila pengguna mengemukakan maklumat borang yang salah atau hilang. 1. Gunakan mesej ralat sebaris untuk memaparkan secara langsung ralat tertentu di sebelah medan yang berkaitan, seperti "Sila masukkan alamat e -mel yang sah", bukannya arahan umum; 2. Tandakan medan masalah secara visual oleh sempadan merah, warna latar belakang atau ikon amaran untuk meningkatkan kebolehbacaan; 3. Apabila borang panjang atau strukturnya kompleks, paparkan ringkasan klik dari ralat yang boleh diklik dan melompat di bahagian atas, tetapi ia perlu digunakan bersama dengan mesej inline; 4. Dayakan pengesahan masa nyata dalam situasi yang sesuai, dan maklum balas segera apabila pengguna memasuki atau meninggalkan medan, seperti memeriksa format e-mel atau kekuatan kata laluan, tetapi mengelakkan mendorong terlalu awal sebelum pengguna mengemukakan. Kaedah ini secara berkesan dapat membimbing pengguna untuk membetulkan kesilapan input dengan cepat dan meningkatkan pengalaman pengisian bentuk.

Yiiexcelsinphpwebdevelopmentduetoitsactiverecordpattern, robustsurity, efisienmvcarchitecture, andperformanceoptimization.1) activerecordsimplifiesdatabaseIntions, reducingdevelopmenttime.2)
