亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home PHP Framework YII Steps to write api interface in yii2

Steps to write api interface in yii2

Nov 06, 2019 pm 05:32 PM
yii2

Steps to write api interface in yii2

yii2寫api接口步驟

Yii2如何實現(xiàn)RESTful風格的API(推薦:《YII教程》?)

1、建立單獨的應用程序

為了增加程序的可維護性,易操作性,我們選擇新建一套應用程序,這也是為了和前臺應用、后臺應用區(qū)分開操作。

在WEB前端(frontend)和后端(backend)的同級目錄,新建一個文件夾,命名api,其目錄結構如下所示:

├─assets
│      AppAsset.php
├─config
│      bootstrap.php
│      main-local.php
│      main.php
│      params-local.php
│      params.php
├─runtime
└─web
    │ index.php
    ├─assets
    └─css

可以看出其目錄結構基本上同backend沒有其他差異,因為我們就是拷貝backend項目,只是做了部分優(yōu)化。

友情提醒,該步驟完成以后,需要修改common\config\bootstrap.php文件,對新建的應用增加alias別名

Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');

2、為新建的api應用程序美化路由

首先保證你的web服務器開啟rewrite規(guī)則,細節(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;
    }
}

最后只需要在應用入口同級增加.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信息

Steps to write api interface in yii2

Steps to write api interface in yii2

Steps to write api interface in yii2

現(xiàn)在,我們的api目錄結構應該多個下面這幾個目錄

│
├─models
│      Goods.php
│
├─modules
│  └─v1
│      │  Module.php
│      │
│      ├─controllers
│      │      DefaultController.php
│      │      GoodsController.php
│      │
│      └─views
│          └─default
│                  index.php

需要說明的是:在生成modules的步驟中,為了使我們的模塊可以訪問,不要忘記在main.php配置文件中添加下面的代碼

<?php    
    ......
    &#39;modules&#39; => [
        &#39;v1&#39; => [
            &#39;class&#39; => &#39;api\modules\v1\Module&#39;,
        ],
    ],
    ......

4、重新配置控制器

為了實現(xiàn)restful風格的api,在yii2中,我們需要對控制器進行一下改寫

<?php
namespace api\modules\v1\controllers;
use yii\rest\ActiveController;
class GoodsController extends ActiveController
{
    public $modelClass = &#39;api\models\Goods&#39;;
}

5、為Goods配置Url規(guī)則

&#39;rules&#39; => [
    [
        &#39;class&#39; => &#39;yii\rest\UrlRule&#39;,
        &#39;controller&#39; => [&#39;v1/goods&#39;]
    ],
]

6、模擬請求操作

經過上面幾個步驟,到此我們已經為goods成功創(chuàng)建了滿足restful風格的api了。為了更好更方便的演示,我們借助工具postman進行模擬請求。

為了見證一下我們的操作,我們用postman請求一下GET /v1/goods看看結果如何:

接著我們先利用gii生成modules后,再利用gii模塊,按照下圖中生成goods信息

Steps to write api interface in yii2

現(xiàn)在,我們的api目錄結構應該多個下面這幾個目錄

從上面截圖中可以清楚的看到,GET /v1/goods 已經能夠很方便的獲取我們表中的數(shù)據(jù)了。

當然,yii2還對該api封裝了如下操作:

GET /users: 逐頁列出所有用戶
HEAD /users: 顯示用戶列表的概要信息
POST /users: 創(chuàng)建一個新用戶
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 支持的動詞

不信的話我們可以利用postman發(fā)送一個post請求到/v1/goods,我們會發(fā)現(xiàn)成功創(chuàng)建了一個新的商品。

需要提醒的是,操作中還請細心且注意:如果你的控制器末端不是復數(shù)(比如是blog非blogs)請保證請求的時候是復數(shù)!這是因為在RESTful架構中,網址中只能有名詞而不能包含動詞,名詞又往往與數(shù)據(jù)表相對應,數(shù)據(jù)表呢又是一個“集合”,因此該名詞往往是復數(shù)的形式。

7、關于授權認證

為什么需要授權認證?這在一般的操作中是需要的。比如說用戶要設置自己的信息。

為了對yii2 restful授權認證說的更清楚,我們將會以兩個兩種不同的方法進行說明。

首先需要開啟認證:

假設我們已經按照第3步創(chuàng)建了包含字段access-token的數(shù)據(jù)表user,而且利用gii上生成了相應的model和controller

配置main.php文件

&#39;components&#39; => [
    &#39;user&#39; => [ 
        &#39;identityClass&#39; => &#39;common\models\User&#39;,
        &#39;enableAutoLogin&#39; => true,
        &#39;enableSession&#39;=>false
    ],
],

為控制器配置authenticator行為指定認證方式

<?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 = &#39;api\models\User&#39;;
    public function behaviors() {
        return ArrayHelper::merge (parent::behaviors(), [ 
                &#39;authenticator&#39; => [ 
                    &#39;class&#39; => QueryParamAuth::className() 
                ] 
        ] );
    }
}

最后我們還需要在identityClass中實現(xiàn)findIdentityByAccessToken方法

public static function findIdentityByAccessToken($token, $type = null)
{
    return static::findOne([&#39;access_token&#39; => $token, &#39;status&#39; => self::STATUS_ACTIVE]);
}

如此一來,我們先通過postman模擬不帶access-token請求看結果

{
  "name": "Unauthorized",
  "message": "You are requesting with an invalid credential.",
  "code": 0,
  "status": 401,
  "type": "yii\\web\\UnauthorizedHttpException"
}

提示401 我們沒有權限訪問!

我們在請求的鏈接上攜帶正確的access-token,認證通過后,控制器會再繼續(xù)執(zhí)行其他檢查(頻率限制、操作權限等),才可以返回正確的用戶信息。

需要提醒的是:通過url的形式對access-token傳遞存在一定的風險,有可能會造成數(shù)據(jù)的泄漏!一般而言,access-token需要放到HTTP頭中進行傳遞!除非客戶端的請求是jsonp格式的!

關于授權認證,我們有一篇更詳細的文章,包括一套完整案例、服務端返回的數(shù)據(jù)類型定義、自定義錯誤機制等。

8、速率限制

速率限制,該操作完全也是出于安全考慮,我們需要限制同一接口某時間段過多的請求。

速率限制默認不啟用,用啟用速率限制,yii\web\User::identityClass 應該實現(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ù)量,比如設置10秒內最多5次請求(小數(shù)量方便我們模擬測試)
    public  function getRateLimit($request, $action){  
         return [5, 10];  
    }
     
    // 回剩余的允許的請求和相應的UNIX時間戳數(shù) 當最后一次速率限制檢查時
    public  function loadAllowance($request, $action){  
         return [$this->allowance, $this->allowance_updated_at];  
    }  
     
    // 保存允許剩余的請求數(shù)和當前的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:相應的UNIX時間戳數(shù)

在我們啟用了速率限制后,Yii 會自動使用 yii\filters\RateLimiter 為 yii\rest\Controller 配置一個行為過濾器來執(zhí)行速率限制檢查。

現(xiàn)在我們通過postman請求v1/users再看看結果,會發(fā)現(xiàn)在10秒內調用超過5次API接口,我們會得到狀態(tài)為429太多請求的異常信息。

{
  "name": "Too Many Requests",
  "message": "Rate limit exceeded.",
  "code": 0,
  "status": 429,
  "type": "yii\\web\\TooManyRequestsHttpException"
}

9、關于版本

為了兼容歷史版本而且考慮向后兼容性,我們在一開始操作的時候就以URL的方式實現(xiàn)了版本話,這里就不再進行闡述了。

10、錯誤處理

Yii的REST框架的HTTP狀態(tài)代碼可參考如下就好,沒啥好說的

200: OK。一切正常。

201: 響應 POST 請求時成功創(chuàng)建一個資源。Location header 包含的URL指向新創(chuàng)建的資源。

204: 該請求被成功處理,響應不包含正文內容 (類似 DELETE 請求)。

304: 資源沒有被修改。可以使用緩存的版本。

400: 錯誤的請求??赡芡ㄟ^用戶方面的多種原因引起的,例如在請求體內有無效的JSON 數(shù)據(jù),無效的操作參數(shù),等等。

401: 驗證失敗。

403: 已經經過身份驗證的用戶不允許訪問指定的 API 末端。

404: 所請求的資源不存在。

405: 不被允許的方法。 請檢查 Allow header 允許的HTTP方法。

415: 不支持的媒體類型。 所請求的內容類型或版本號是無效的。

422: 數(shù)據(jù)驗證失敗 (例如,響應一個 POST 請求)。 請檢查響應體內詳細的錯誤消息。

429: 請求過多。 由于限速請求被拒絕。

500: 內部服務器錯誤。 這可能是由于內部程序錯誤引起的。

The above is the detailed content of Steps to write api interface in yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Yii vs. Laravel: Choosing the Right PHP Framework for Your Project Yii vs. Laravel: Choosing the Right PHP Framework for Your Project Jul 02, 2025 am 12:26 AM

The choice of Yii or Laravel depends on project requirements and team expertise. 1) Yii is suitable for high performance needs and has a lightweight structure. 2) Laravel provides rich functions, is developer-friendly and suitable for complex applications. Both are scalable, but Yii is easier to modular, while Laravel community is more resourceful.

How do I use the beforeAction() and afterAction() methods in a controller? How do I use the beforeAction() and afterAction() methods in a controller? Jul 02, 2025 am 12:03 AM

beforeAction() is used in Yii2 to run logic before the controller action is executed. If permission checks or requests modification, it must return true or parent class call to continue execution; afterAction() is run after the action is executed and before the response is sent, which is suitable for output modification or logging. 1.beforeAction() is run before the action is executed, and can be used for user permission verification. For example, redirecting the unlogged user to the login page, you need to return parent::beforeAction($action) or true to continue the process, otherwise the action execution will be prevented; 2. You can skip the check of a specific action by checking $action->id; 3. AfterAc

Laravel MVC: real code samples Laravel MVC: real code samples Jul 03, 2025 am 12:35 AM

Laravel's MVC architecture consists of a model, a view and a controller, which are responsible for data logic, user interface and request processing respectively. 1) Create a User model to define data structures and relationships. 2) UserController processes user requests, including listing, displaying and creating users. 3) The view uses the Blade template to display user data. This architecture improves code clarity and maintainability.

What are Yii asset bundles, and what is their purpose? What are Yii asset bundles, and what is their purpose? Jul 07, 2025 am 12:06 AM

YiiassetbundlesorganizeandmanagewebassetslikeCSS,JavaScript,andimagesinaYiiapplication.1.Theysimplifydependencymanagement,ensuringcorrectloadorder.2.Theypreventduplicateassetinclusion.3.Theyenableenvironment-specifichandlingsuchasminification.4.Theyp

How do I render a view from a controller? How do I render a view from a controller? Jul 07, 2025 am 12:09 AM

In the MVC framework, the mechanism for the controller to render views is based on the naming convention and allows explicit overwriting. If redirection is not explicitly indicated, the controller will automatically find a view file with the same name as the action for rendering. 1. Make sure that the view file exists and is named correctly. For example, the view path corresponding to the action show of the controller PostsController should be views/posts/show.html.erb or Views/Posts/Show.cshtml; 2. Use explicit rendering to specify different templates, such as render'custom_template' in Rails and view('posts.custom_template') in Laravel

How do I save data to the database using Yii models? How do I save data to the database using Yii models? Jul 05, 2025 am 12:36 AM

When saving data to the database in the Yii framework, it is mainly implemented through the ActiveRecord model. 1. Creating a new record requires instantiation of the model, loading the data and verifying it before saving; 2. Updating the record requires querying the existing data before assignment; 3. When using the load() method for batch assignment, security attributes must be marked in rules(); 4. When saving associated data, transactions should be used to ensure consistency. The specific steps include: instantiating the model and filling the data with load(), calling validate() verification, and finally performing save() persistence; when updating, first obtaining records and then assigning values; when sensitive fields are involved, massassignment should be restricted; when saving the associated model, beginTran should be combined

How do I create a basic route in Yii? How do I create a basic route in Yii? Jul 09, 2025 am 01:15 AM

TocreateabasicrouteinYii,firstsetupacontrollerbyplacingitinthecontrollersdirectorywithpropernamingandclassdefinitionextendingyii\web\Controller.1)Createanactionwithinthecontrollerbydefiningapublicmethodstartingwith"action".2)ConfigureURLstr

How do I create custom actions in a Yii controller? How do I create custom actions in a Yii controller? Jul 12, 2025 am 12:35 AM

The method of creating custom operations in Yii is to define a common method starting with an action in the controller, optionally accept parameters; then process data, render views, or return JSON as needed; and finally ensure security through access control. The specific steps include: 1. Create a method prefixed with action; 2. Set the method to public; 3. Can receive URL parameters; 4. Process data such as querying the model, processing POST requests, redirecting, etc.; 5. Use AccessControl or manually checking permissions to restrict access. For example, actionProfile($id) can be accessed via /site/profile?id=123 and renders the user profile page. The best practice is

See all articles