我的配置中有以下内容:
'modules' => [
'v0' => [
'class' => 'app\modules\v0\Module',
],
'v1' => [
'class' => 'app\modules\v1\Module',
],
],
以下网址管理员条目:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing'=>true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v0/customer','v0/object']],
]
我有以下api调用更新(PUT),查看(GET),删除(删除):
https://myapi.com/v0/objects/12345?name=warehouse
https://myapi.com/v0/objects/12345?name=product
我希望用户能够使用以下格式访问它:https://myapi.com/v0/objects/warehouse/12345
我已经看过重写规则,但我认为该模块可能很棘手。有人可以为我解释一下吗?
我的网站/ .htaccess看起来像这样:
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
答案 0 :(得分:1)
无论如何 - 这有效 - 我使用模式(而不是extraPatterns),因为我想自己明确定义所有规则。
['class' => 'yii\rest\UrlRule', 'controller' => ['v0/object'], 'patterns'=>[
'GET <name>/<id>'=>'view',
'PUT <name>/<id>'=>'update',
'DELETE <name>/<id>'=>'delete',
'POST <name>'=>'create',
'GET <name>'=>'index',
]],
答案 1 :(得分:0)
尝试这样的事情......(未经测试)
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v0/object',
'extraPatterns' => [
'GET <name:[\w-]+>/<id:\d+>' => 'view',
'PUT <name:[\w-]+>/<id:\d+>' => 'update',
'DELETE <name:[\w-]+>/<id:\d+>' => 'delete',
],
],
],
假设您在ObjectController中有这些方法:
public function actionView($id, $name)
public function actionUpdate($id, $name)
public function actionDelete($id, $name)
如果你从yii \ rest \ controller扩展ObjectController,要小心,因为它定义了update / view / delete / index的默认值(问题没有说明)。如果是这样,我会重命名上面的方法并使用&#39; only&#39;指令只包含控制器的这些方法。