• 【规范】resetful api 基于yiibasic 实现


    参考yii2的手册

    1.使用yii reset的路由规则

    'urlManager' => [
                'enablePrettyUrl' => true,
                'enableStrictParsing' => true,
                'showScriptName' => false,
                'rules' => [
                    [
                        'class' => 'yii\rest\UrlRule',
                        'controller' => 'goods',//可为数组形式
                        'pluralize' => false, //设置是否使用复数访问资源
                        
                    ],
                ],
            ],

    2.改写服务器的重写规则,apache的web同级目录新建.htaccess文件

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [L]

    3.新建模型为app/models/Goods.php

    /**
     * This is the model class for table "goods".
     *
     * @property integer $id
     * @property string $name
     */
    class Goods extends \yii\db\ActiveRecord
    {
        /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return 'goods';
        }
    
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [['name'], 'string', 'max' => 1],
            ];
        }
    
        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'id' => 'ID',
                'name' => 'Name',
            ];
        }
        public function view()
        {
            return ['name'];
        }
    
    }

    4.新建数据表

    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');

    5.新建控制器 app\controllers\GoodsController

    <?php
    
    namespace app\controllers;
    
    use yii\rest\ActiveController;
    
    class GoodsController extends ActiveController
    {
        public $modelClass = 'app\models\Goods';
    
    }

    6.OK,本人用的是Restlet Client 工具

  • 相关阅读:
    Android JNI用于驱动測试
    shell实例浅谈之三产生随机数七种方法
    WEB安全实战(二)带你认识 XSS 攻击
    前端和云端性能分析工具分析报告
    【翻译】Ext JS——高效的编码风格指南
    dubbo协议
    JavaBean对象转map
    messagePack编解码
    主流编码框架
    java编解码技术,json序列化与二进制序列化
  • 原文地址:https://www.cnblogs.com/jysdhr/p/6867423.html
Copyright © 2020-2023  润新知