无法找到我自定义构建Yii2 API页面的网址

时间:2018-04-09 08:39:56

标签: yii2

还是YII2的新手,我正在开发一个已经建立的YII2项目(当场学习),但我找不到新添加的API页面的正确URL /路径。 不确定代码中是否缺少某些内容,错误的路径或其他内容。

如果尝试过: (不在localhost上工作)

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 /配置/ 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 /模块/ V1 /控制器/ 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 /模块/ V1 /模型/ 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 /模块/ 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 /网络/ 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 /网络/ 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

3 个答案:

答案 0 :(得分:0)

尝试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

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

首先,你的控制器中为$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方法
  7. 了解Extending ActiveController

    关于创建自定义操作

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

      

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

    阅读更多here

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

    BasicController

    您的控制器将如下所示

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