首页 > 在Yii2框架中使用Rest时,怎样配置能有businesses/353/products/123的访问形式

在Yii2框架中使用Rest时,怎样配置能有businesses/353/products/123的访问形式

我在学习Restful Api时,参考了这篇文章:RESTful API 设计指南,里面有介绍到这种形式的访问方式:

DELETE /zoos/ID/animals/ID:删除某个指定动物园的指定动物

而恰好我的项目中也有这种需求:

GET businesses/1233/products
DELETE businesses/1233/products/1235

我使用Yii2框架自带的Rest,做到了这种形式的访问方式:

GET http://xxx.xxx.com/web/v1/businesses/353

但不知道怎么能做到这种访问方式:

GET http://xxx.xxx.com/web/v1/businesses/353/products

我猜想是在urlManager的rules下配置,但不知道该怎么做,望大家多多指教,谢谢!!!


使用 Yii2 的route 也可以做,不要拘泥于框架提供的 \yii\rest\UrlRule, 实际情况很少能不加改动地直接用, 或许可以说官方只是提供一个参考的样例,你大可以自己写套自己的 UrlRule。

'POST,GET,DELETE web/v1/business/<business_id:\d+>/products/<product_id:\d+>' => 'v1/business/products'

'DELETE web/v1/business/<business_id:\d+>/products/<product_id:\d+>' => 'v1/business/delete-products'

'POST web/v1/business/<business_id:\d+>/products/<product_id:\d+>' => 'v1/business/post-products'

'GET web/v1/business/<business_id:\d+>/products/<product_id:\d+>' => 'v1/business/get-products'

参考: http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html


需要做这么几件事情:

  1. 配置Apache(如果用的是nginx,则参考nginx配置)
    在httpd.conf文件中打开:

    LoadModule rewrite_module libexec/apache2/mod_rewrite.so
    

找到DocumentRoot的Directory,把下面的内容改为

AllowOverride All

如果有虚拟主机,则需要在相应的虚拟主机里修改。

  1. 在需要改写的文件夹里的web文件夹下,添加一个文件名为.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

  2. 在相应的config文件夹下,在main.php中添加:

    'urlManager' => [

               'enablePrettyUrl' => true,
               'enableStrictParsing' => false,
               'showScriptName' => false,
               'rules' => [
                   ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
               ],
           ],
    
  3. 相应的controller,头部写法如下:

    <?php

    namespace app\controllers;

    use yii\rest\ActiveController;

    class ProductController extends ActiveController
    {

       public $modelClass = 'common\models\Product';

    }

然后就可以用products/123来访问了。

【热门文章】
【热门文章】