国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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風(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ī)則,細節(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信息

Steps to write api interface in yii2

Steps to write api interface in yii2

Steps to write api interface in yii2

現(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    
    ......
    &#39;modules&#39; => [
        &#39;v1&#39; => [
            &#39;class&#39; => &#39;api\modules\v1\Module&#39;,
        ],
    ],
    ......

4、重新配置控制器

為了實現(xiàn)restful風(fēng)格的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、模擬請求操作

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

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

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

Steps to write api interface in yii2

現(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 的詳細信息
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)建了一個新的商品。

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

7、關(guān)于授權(quán)認證

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

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

首先需要開啟認證:

假設(shè)我們已經(jīng)按照第3步創(chuàng)建了包含字段access-token的數(shù)據(jù)表user,而且利用gii上生成了相應(yīng)的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請求看結(jié)果

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

提示401 我們沒有權(quán)限訪問!

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

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

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

8、速率限制

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

速率限制默認不啟用,用啟用速率限制,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: 資源沒有被修改。可以使用緩存的版本。

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)詳細的錯誤消息。

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

500: 內(nèi)部服務(wù)器錯誤。 這可能是由于內(nèi)部程序錯誤引起的。

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)

How do I configure a Yii widget? How do I configure a Yii widget? Jun 18, 2025 am 12:01 AM

ToconfigureaYiiwidget,youcallitwithaconfigurationarraythatsetspropertiesandoptions.1.Usethesyntax\\yii\\widgets\\ClassName::widget($config)inyourview.2.Definethe$configarraywithkeysmatchingthewidget’spublicproperties.3.Somewidgetssupportnestedarraysf

How do I install Yii on my operating system (Windows, macOS, Linux)? How do I install Yii on my operating system (Windows, macOS, Linux)? Jun 17, 2025 am 09:21 AM

To install the Yii framework, you need to configure PHP and Composer according to different operating systems. The specific steps are as follows: 1. You need to manually download PHP and configure environment variables on Windows, then install Composer, use commands to create a project and run a built-in server; 2. It is recommended to use Homebrew to install PHP and Composer, then create a project and start a development server; 3. Linux (such as Ubuntu) install PHP, extensions and Composer through apt, then create a project and deploy a formal environment with Apache or Nginx. The main differences between different systems are in the environment construction stage. Once PHP and Composer are ready, the subsequent processes are consistent. Note

How do I display validation errors in a form? How do I display validation errors in a form? Jun 19, 2025 am 12:02 AM

It is crucial to clearly display verification errors when the user submits the form information incorrectly or missing. 1. Use inline error messages to directly display specific errors next to the relevant fields, such as "Please enter a valid email address", rather than general prompts; 2. Mark the problem fields visually by red borders, background colors or warning icons to enhance readability; 3. When the form is long or the structure is complex, display a click-through summary of the error that can be clicked and jumped at the top, but it needs to be used in conjunction with inline messages; 4. Enable real-time verification in the appropriate situation, and instant feedback when the user enters or leaves the field, such as checking the email format or password strength, but avoiding prompting too early before the user submits. These methods can effectively guide users to quickly correct input errors and improve the form filling experience.

Top Skills Every Yii Framework Developer Needs Top Skills Every Yii Framework Developer Needs Jun 20, 2025 am 12:03 AM

Key skills to become a Yii framework developer include: 1) proficient in PHP and object-oriented programming (OOP), 2) understand MVC architecture, 3) proficient in using Yii's ActiveRecord, 4) familiar with Yii's Gii tools, 5) master RESTful API development, 6) possess front-end integration skills, 7) master debugging and performance optimization, 8) continuous learning and community participation. These skills combined can help developers work efficiently in the Yii framework.

How do I create forms in Yii? How do I create forms in Yii? Jun 23, 2025 am 12:03 AM

The core process of creating a form in the Yii framework includes four steps: 1. Create a model class, define fields and verification rules; 2. Process the form submission and verification logic in the controller; 3. Render form elements in the view using ActiveForm; 4. Pay attention to CSRF protection, layout and style configuration. The model class sets the required items and data formats through the rules() method. The controller uses load() and validate() to process the submitted data. The view uses ActiveForm to automatically generate input boxes with labels and error prompts, and can customize the layout and styles, thereby achieving a complete form system.

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

Is Yii developers a job with future? Is Yii developers a job with future? Jun 22, 2025 am 12:09 AM

Yii developers' career prospects still exist, but require diversified skills. 1) Yii still has demand in enterprise applications, but the market competition is fierce. 2) Yii skills can be transferred to other PHP frameworks. 3) Yii community has small support but sufficient resources. 4) Improve career flexibility by learning other frameworks and keeping Yii updated.

See all articles