我在学习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下配置,但不知道该怎么做,望大家多多指教,谢谢!!!
需要做这么几件事情:
配置Apache(如果用的是nginx,则参考nginx配置)
在httpd.conf文件中打开:
找到DocumentRoot的Directory,把下面的内容改为
如果有虚拟主机,则需要在相应的虚拟主机里修改。
在需要改写的文件夹里的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
在相应的config文件夹下,在main.php中添加:
'urlManager' => [
相应的controller,头部写法如下:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class ProductController extends ActiveController
{
}
然后就可以用products/123来访问了。