【问题标题】:Cant find the url for my custom build Yii2 API page找不到我的自定义构建 Yii2 API 页面的 url
【发布时间】:2018-04-09 08:39:56
【问题描述】:

对 YII2 还是新手,我正在处理一个已经构建的 YII2 项目(现场学习),但我找不到新添加的 API 页面的正确 url/路径。 不确定代码中是否缺少某些内容、路径错误或其他原因。

如果尝试过: (不适用于本地主机)

www.example.com/v1/product/
www.example.com/web/product
www.example.com/v1/product/web/product

...

应用结构

+ api
  + config
    - main.php
 + modules
   + v1
     + controllers
       - ProductController.php
     + models
       - Product.php
     - RestModule.php
 + web
   - .htaccess
   - index.php
+ backend
+ common
+ frontend

api/config/main.php

<?php

return [
    'id' => 'app-api',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'modules' => [
        'v1' => [
            'class' => 'api\modules\v1\RestModule',
        ]
    ],
    'components' => [
        'request' => [
              'parsers' => [
                 'application/json' => 'yii\web\JsonParser',
              ],
        ],
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => false,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'v1/product',
                ]
            ],
        ]
    ]
];

api/modules/v1/controllers/ProductController.php

<?php

namespace api\modules\v1\controllers;

class ProductController extends yii\rest\ActiveController
{
    public $modelClass = 'api\models\v1\models\Product';

    public function actionIndex(){

        echo 'product controller';

    }

}

api/modules/v1/models/Product.php

<?php

namespace api\modules\v1\models;

class Product extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return 'product';
    }

    public function rules()
    {
        return [
            [['description', 'name'], 'string']
        ];
    }
}

api/modules/RestModule.php

<?php

namespace api\modules\v1;

class RestModule extends \yii\base\Module
{

    public $controllerNamespace = 'api\modules\v1\controllers';

    public function init()
    {
        parent::init();

        echo 'restmodule';

    }

}

api/web/index.php

<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/aliases.php');

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../../common/config/main-local.php'),
    require(__DIR__ . '/../config/main.php'),
}

$application = new yii\web\Application($config);
$application->run();

api/web/.htaccess

RewriteEngine on

# Order Deny,Allow
# Deny from all
# Allow from 10.30.2.0/24
# Allow from 37.153.242.179

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.(gif|png|jpg|jpeg)$ /img/blank.gif [L,R=302]

# 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

【问题讨论】:

  • 查看答案是否对您有帮助

标签: yii2


【解决方案1】:

试试www.example.com/v1/products

您可能已经注意到,控制器 ID user 在端点 URL 中以复数形式显示为 users。这是因为yii\rest\UrlRule 在创建子 URL 规则时会自动将控制器 ID 复数。您可以通过将yii\rest\UrlRule::$pluralize 设置为false 来禁用此行为。

https://www.yiiframework.com/doc/guide/2.0/en/rest-routing

【讨论】:

  • @user759235 您可以尝试www.example.com/productswww.example.com/api/web/products,但如果不知道您的虚拟主机配置,就很难猜到。
【解决方案2】:

试试这个

    www.example.com/api/v1/product/

【讨论】:

  • 尝试添加 index.php,例如 www.example.com/index.php/api/v1/product/
  • 'v1' => [ 'class' => 'api\modules\v1\Module', ] 在你的 api/config/main.php 文件中用 Module 替换 RestModule
  • 也没有回应
【解决方案3】:

首先,您在控制器内部为 $modelClass 属性定义了错误的命名空间,它应该是

public $modelClass = 'api\modules\v1\models\Product';

而不是

public $modelClass = 'api\models\v1\models\Product';

您将 modules 拼错为 models,因此将您的控制器更改为以下内容并从您的控制器中删除 actionIndex()

<?php

namespace api\modules\v1\controllers;

class ProductController extends yii\rest\ActiveController {

    public $modelClass = 'api\modules\v1\models\Product';

}

yii\rest\UrlRule 自动将控制器 ID 复数,您可以通过 www.example.com/v1/products 访问它,它将以 json 格式显示产品表中可用的所有记录,因为您正在扩展 ActiveController .

默认情况下,yii\rest\ActiveController 提供以下操作:

  1. index:逐页列出资源;
  2. view:返回指定资源的详细信息;
  3. create:新建资源;
  4. update:更新现有资源;
  5. delete:删除指定资源;
  6. options:返回支持的 HTTP 方法

了解Extending ActiveController

关于创建自定义操作

Yii 提供了两个基本控制器类来简化您创建 RESTful 操作的工作:yii\rest\Controlleryii\rest\ActiveController

这两个控制器的区别在于后者 提供一组默认操作,专门设计用于 处理表示为 Active Record 的资源。所以如果你正在使用 Active Record 并且对提供的内置操作感到满意, 你可以考虑扩展你的控制器类 yii\rest\ActiveController,它将让您创建强大的 具有最少代码的 RESTful API。

阅读更多here

因此,如果您打算创建自己的操作,您可以创建一个扩展 yii\rest\Controlleryii\rest\ActiveController 的控制器,请参阅下面的控制器尝试使用邮递员应用程序或 curl 将其复制到您的 api\modules\v1\controllers 文件夹并调用它www.example.com/v1/basics/test。此外,为了使用您使用的任何自定义操作名称,您应该在 extraPatterns 选项内为 UrlRule 定义操作,例如,如果您打算使用在BasicController 中命名test 会检索一些信息并返回响应,您的规则应如下所示

[
        'class' => 'yii\rest\UrlRule' ,
        'controller' => 'v1/basic' ,
        'extraPatterns' => [
            'GET test' => 'test' ,
        ] ,
        'tokens' => [
            '{id}' => '<id:\\w+>'
        ]
    ]

您的控制器将如下所示

<?php

namespace api\modules\v1\controllers;

use yii\rest\Controller;

class BasicController extends Controller {

    public function actionTest() {
        return "oho";
    }

}

【讨论】:

  • 感谢信息(解释了很多),没有看到错字,遗憾的是这不会使它工作。
  • 我今天刚刚实现了一个 API,并且以同样的方式实现了它,它工作得很好,什么不起作用你是否按照我所说的每件事 @user759235
猜你喜欢
  • 1970-01-01
  • 2017-09-23
  • 2022-07-13
  • 2015-01-14
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多