Yii2实现RESTful风格的API中要注意的坑有哪些呢
更新:HHH   时间:2023-1-7


本篇文章给大家分享的是有关Yii2实现RESTful风格的API中要注意的坑有哪些呢,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

Yii2实现RESTful风格的API的流程如下:
1、WEB前端(frontend)和后端(backend)的同级目录,新建一个文件夹,命名api,api中文件完全复制一份原始的backend中文件即可

2、需要修改common\config\bootstrap.php文件,对新建的应用增加alias别名

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

3、保证你的web服务器开启rewrite规则!配置apache或nginx!这里请google或百度下。
nginx中在conf文件夹中vhost.conf或nginx.conf中相关位置加入:

location / {
try_files $uri $uri/ /index.php$is_args$args;
}

apache中在对应的api/web(域名指向的服务器目录中)加入.htaccess:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule . index.php

4、api应用程序美化路由(注意里面的括弧、名字的大小写,类名习惯驼峰式,但是controller 对应的控制器名一定要小写)
接着配置api/config/main.php文件

'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,

        'rules' => [
            ['class'=>'yii\rest\UrlRule','controller'=>'article'],
        ],
    ],

如果担心影响其他访问地址(如gii无法连接)可以先注释'enableStrictParsing' =>true,传到服务器后开启即可(增加安全性)

5、准备工作好啦,开始写conroller与model:
在www根目录-->common-->models中新建文件Article.php(可以使用Gii)

<?php

namespace common\models;

use Yii;

/**

  • This is the model class for table "article".


  • @property int $id ID

  • @property string $title 标题

  • @property string $content 内容

  • @property int $category_id 分类

  • @property int $status 状态

  • @property int $created_by 创建人

  • @property int $created_at 创建时间

  • @property int $updated_at 最后修改时间
    */
    class Article extends \yii\db\ActiveRecord
    {
    /**

    /**

    /**

    • @inheritdoc
      */
      public function attributeLabels()
      {
      return [
      'id' => 'ID',
      'title' => 'Title',
      'content' => 'Content',
      'category_id' => 'Category ID',
      'status' => 'Status',
      'created_by' => 'Created By',
      'created_at' => 'Created At',
      'updated_at' => 'Updated At',
      ];
      }
      }

    • @inheritdoc
      */
      public function rules()
      {
      return [
      [['id', 'title', 'content'], 'required'],
      [['id', 'category_id', 'status', 'created_by', 'created_at', 'updated_at'], 'integer'],
      [['content'], 'string'],
      [['title'], 'string', 'max' => 512],
      ];
      }

    • @inheritdoc
      */
      public static function tableName()
      {
      return 'article';
      }

然后在api中controllers中新建文件:ArticleController.php

<?php
namespace api\controllers;
use yii\rest\ActiveController;
use common\models\Article;
/**

  • */
    class ArticleController extends ActiveController
    {

    // function __construct(argument)
    // {
    //  # code...
    // }
    public $modelClass='\common\models\Article';
    }

6、访问链接查看接口返回值:
http://www.xxx.com/articles  已经能够很方便的获取我们表中的数据了。
当然,yii2还对该api封装了如下操作:

GET /articles: 逐页列出所有用户
HEAD /articles: 显示用户列表的概要信息
POST /articles: 创建一个新用户
GET /articles/123: 返回用户 123 的详细信息
HEAD /articles/123: 显示用户 123 的概述信息
PATCH /articles/123 and PUT /users/123: 更新用户123
DELETE /articles/123: 删除用户123
OPTIONS /articles: 显示关于末端 /users 支持的动词
OPTIONS /articles/123: 显示有关末端 /users/123 支持的动词

以上就是Yii2实现RESTful风格的API中要注意的坑有哪些呢,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注天达云行业资讯频道。

返回web开发教程...