zoukankan      html  css  js  c++  java
  • 关于yii2 REST api 的问题

    首先,需要在basic/web/文件夹下添加一个.htaccess文件

    这样进入项目就会自动访问index.php文件,url就不会错乱了

    <IfModule mod_rewrite.c>
    
    Options +FollowSymLinks
    
    IndexIgnore */*
    
    RewriteEngine on
    
    # if a directory or a file exists, use it directly
    
    RewriteCond %{REQUEST_FILENAME} !-f
    
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # otherwise forward it to index.php
    
    RewriteRule . index.php
    
    </IfModule>

    接下来详解一下官方文档里的东西

    首先,创建一个 yiidbActiveRecord 类appmodelsUser来访问user表

    然后,创建一个控制器类 appcontrollersUserController 如下,

    <?php
    
    namespace appcontrollers;
    
    use yii
    estActiveController;
    
    class UserController extends ActiveController
    {
        public $modelClass = 'appmodelsUser';
    }

    Then, modify the configuration about the urlManager component in your application configuration:

    'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            ['class' => 'yii
    estUrlRule', 'controller' => 'user'],
        ],
    ]
        // 用于表明urlManager是否启用URL美化功能,在Yii1.1中称为path格式URL,
        // Yii2.0中改称美化。
        // 默认不启用。但实际使用中,特别是产品环境,一般都会启用。
        public $enablePrettyUrl = false;
    
        // 是否启用严格解析,如启用严格解析,要求当前请求应至少匹配1个路由规则,
        // 否则认为是无效路由。
        // 这个选项仅在 enablePrettyUrl 启用后才有效。
        public $enableStrictParsing = false;
    // 指定是否在URL在保留入口脚本 index.php
        public $showScriptName = true;

    改成上述设置后,http://localhost/basic/web/users 可以直接访问api(注意自动帮你加了个s)

    现在来详解一下一个urlManager的配置规则:

            'urlManager' => [
              'enablePrettyUrl' => true,//true 打开美化
              'enableStrictParsing' => true,//true启用严格解析,要求当前请求应至少匹配1个路由规则,不给路由就404,例如http://localhost/basic/web/就会404;false就是自己找index
              'showScriptName' => false,//指定是否在URL在保留入口脚本 index.php
                'rules' => [
                    ['class' => 'yii
    estUrlRule', 
                     'controller' => 'user', 
                     'pluralize'=>true], //true需要访问users; false需要访问user,默认是true
                ],
            ],        
    • GET /users: 逐页列出所有用户
    • HEAD /users: 显示用户列表的概要信息
    • POST /users: 创建一个新用户
    • GET /users/123: 返回用户 123 的详细信息
    • HEAD /users/123: 显示用户 123 的概述信息
    • PATCH /users/123 and PUT /users/123: 更新用户123
    • DELETE /users/123: 删除用户123
    • OPTIONS /users: 显示关于末端 /users 支持的动词
    • OPTIONS /users/123: 显示有关末端 /users/123 支持的动词
  • 相关阅读:
    C# 反射 通过类名创建类实例
    c#委托把方法当成参数
    PPT美化大师
    以Outlook样式分组和排列数据项
    使用windows服务和MSMQ和进行日志管理(解决高并发问题)
    springboot配置filter
    filter 中用spring StopWatch 监控请求执行时间
    spring计时工具类stopwatch用法
    Spring异步任务处理,@Async的配置和使用
    注解用法详解——@SuppressWarnings
  • 原文地址:https://www.cnblogs.com/turtle920/p/4966513.html
Copyright © 2011-2022 走看看