【发布时间】: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