【规范】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 工具

posted @ 2017-05-17 14:32  jysdhr  阅读(364)  评论(0编辑  收藏  举报