国产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寫(xiě)api接口步驟

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

1、建立單獨(dú)的應(yīng)用程序

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

在WEB前端(frontend)和后端(backend)的同級(jí)目錄,新建一個(gè)文件夾,命名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沒(méi)有其他差異,因?yàn)槲覀兙褪强截恇ackend項(xiàng)目,只是做了部分優(yōu)化。

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

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

2、為新建的api應(yīng)用程序美化路由

首先保證你的web服務(wù)器開(kāi)啟rewrite規(guī)則,細(xì)節(jié)我們就不說(shuō)了,不過(guò)這是前提。

接著配置api/config/main.php文件

'components' => [
    // other config
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' =>true,
        'rules' => [],
    ]
],

開(kāi)啟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)用入口同級(jí)增加.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生成測(cè)試modules

用了便于演示說(shuō)明,我們新建一張數(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)該多個(gè)下面這幾個(gè)目錄

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

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

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

4、重新配置控制器

為了實(shí)現(xiàn)restful風(fēng)格的api,在yii2中,我們需要對(duì)控制器進(jìn)行一下改寫(xiě)

<?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、模擬請(qǐng)求操作

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

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

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

Steps to write api interface in yii2

現(xiàn)在,我們的api目錄結(jié)構(gòu)應(yīng)該多個(gè)下面這幾個(gè)目錄

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

當(dāng)然,yii2還對(duì)該api封裝了如下操作:

GET /users: 逐頁(yè)列出所有用戶
HEAD /users: 顯示用戶列表的概要信息
POST /users: 創(chuàng)建一個(gè)新用戶
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 支持的動(dòng)詞
OPTIONS /users/123: 顯示有關(guān)末端 /users/123 支持的動(dòng)詞

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

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

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

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

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

首先需要開(kāi)啟認(rè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行為指定認(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 = &#39;api\models\User&#39;;
    public function behaviors() {
        return ArrayHelper::merge (parent::behaviors(), [ 
                &#39;authenticator&#39; => [ 
                    &#39;class&#39; => QueryParamAuth::className() 
                ] 
        ] );
    }
}

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

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

如此一來(lái),我們先通過(guò)postman模擬不帶access-token請(qǐng)求看結(jié)果

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

提示401 我們沒(méi)有權(quán)限訪問(wèn)!

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

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

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

8、速率限制

速率限制,該操作完全也是出于安全考慮,我們需要限制同一接口某時(shí)間段過(guò)多的請(qǐng)求。

速率限制默認(rèn)不啟用,用啟用速率限制,yii\web\User::identityClass 應(yīng)該實(shí)現(xiàn)yii\filters\RateLimitInterface,也就是說(shuō)我們的common\models\User.php需要實(shí)現(xiàn)yii\filters\RateLimitInterface接口的三個(gè)方法,具體代碼可參考:

use yii\filters\RateLimitInterface;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface, RateLimitInterface
{
    // other code ...... 
    // 返回某一時(shí)間允許請(qǐng)求的最大數(shù)量,比如設(shè)置10秒內(nèi)最多5次請(qǐng)求(小數(shù)量方便我們模擬測(cè)試)
    public  function getRateLimit($request, $action){  
         return [5, 10];  
    }
     
    // 回剩余的允許的請(qǐng)求和相應(yīng)的UNIX時(shí)間戳數(shù) 當(dāng)最后一次速率限制檢查時(shí)
    public  function loadAllowance($request, $action){  
         return [$this->allowance, $this->allowance_updated_at];  
    }  
     
    // 保存允許剩余的請(qǐng)求數(shù)和當(dāng)前的UNIX時(shí)間戳
    public  function saveAllowance($request, $action, $allowance, $timestamp){ 
        $this->allowance = $allowance;  
        $this->allowance_updated_at = $timestamp;  
        $this->save();  
    }  
}

需要注意的是,你仍然需要在數(shù)據(jù)表User中新增加兩個(gè)字段

allowance:剩余的允許的請(qǐng)求數(shù)量

allowance_updated_at:相應(yīng)的UNIX時(shí)間戳數(shù)

在我們啟用了速率限制后,Yii 會(huì)自動(dòng)使用 yii\filters\RateLimiter 為 yii\rest\Controller 配置一個(gè)行為過(guò)濾器來(lái)執(zhí)行速率限制檢查。

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

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

9、關(guān)于版本

為了兼容歷史版本而且考慮向后兼容性,我們?cè)谝婚_(kāi)始操作的時(shí)候就以URL的方式實(shí)現(xiàn)了版本話,這里就不再進(jìn)行闡述了。

10、錯(cuò)誤處理

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

200: OK。一切正常。

201: 響應(yīng) POST 請(qǐng)求時(shí)成功創(chuàng)建一個(gè)資源。Location header 包含的URL指向新創(chuàng)建的資源。

204: 該請(qǐng)求被成功處理,響應(yīng)不包含正文內(nèi)容 (類似 DELETE 請(qǐng)求)。

304: 資源沒(méi)有被修改??梢允褂镁彺娴陌姹尽?/p>

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

401: 驗(yàn)證失敗。

403: 已經(jīng)經(jīng)過(guò)身份驗(yàn)證的用戶不允許訪問(wèn)指定的 API 末端。

404: 所請(qǐng)求的資源不存在。

405: 不被允許的方法。 請(qǐng)檢查 Allow header 允許的HTTP方法。

415: 不支持的媒體類型。 所請(qǐng)求的內(nèi)容類型或版本號(hào)是無(wú)效的。

422: 數(shù)據(jù)驗(yàn)證失敗 (例如,響應(yīng)一個(gè) POST 請(qǐng)求)。 請(qǐng)檢查響應(yīng)體內(nèi)詳細(xì)的錯(cuò)誤消息。

429: 請(qǐng)求過(guò)多。 由于限速請(qǐng)求被拒絕。

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

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

Yii Framework: Unique Features That Make It a Great Choice Yii Framework: Unique Features That Make It a Great Choice Jun 13, 2025 am 12:02 AM

YiiFrameworkexcelsduetoitsspeed,security,andscalability.1)Itoffershighperformancewithlazyloadingandcaching.2)RobustsecurityfeaturesincludeCSRFprotectionandsecuresessionmanagement.3)Itsmodulararchitecturesupportseasyscalabilityforgrowingapplications.

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.

Yii Framework: Essential Features That Make It a Top Performer Yii Framework: Essential Features That Make It a Top Performer Jun 14, 2025 am 12:09 AM

YiiexcelsinPHPwebdevelopmentduetoitsActiveRecordpattern,robustsecurity,efficientMVCarchitecture,andperformanceoptimization.1)ActiveRecordsimplifiesdatabaseinteractions,reducingdevelopmenttime.2)Built-insecurityfeaturesprotectagainstattackslikeSQLinje

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.

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

See all articles