Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于路由映射与代码组织的矛盾 #4

Closed
dearbird opened this issue Apr 6, 2016 · 4 comments
Closed

关于路由映射与代码组织的矛盾 #4

dearbird opened this issue Apr 6, 2016 · 4 comments

Comments

@dearbird
Copy link

dearbird commented Apr 6, 2016

假设有两个API

  1. Get /users/100/Devices
  2. Get /catalogs/200/Devices

按照 phprs 的规则,应该放在不同的文件中,如 users.php, catalogs.php
但是两个api处理的资源都是Device, 似乎又应该放在一个文件中。
实践上怎么处理比较好?

@lloydzhou
Copy link

controller确实应该放在不同的文件夹,至于你说的处理的资源一样,那就是操作相同的model嘛!这有什么难以理解的?

@dearbird
Copy link
Author

dearbird commented Apr 7, 2016

如果是MVC模式的话,这样处理是没问题的,但是以phprs的规则来看,似乎并没有对嵌套资源的情况有优化。
按我的理解, /users/100/Devices 和 /catalogs/200/Devices 两个路由应该放在同一个类里面,但是它们的url第一段是不一样的,因此有困惑。

@caoym
Copy link
Collaborator

caoym commented Apr 7, 2016

如果要套用MVC模式,可以考虑将users和catalogs当做Controller,Devices当做model。
当然,如果只是想把 /users/100/Devices 和 /catalogs/200/Devices 放在一个类里,也是有办法的。

可以定义一个如Devices类:

/** @path("/")*/
class Devices{
      /**@route({"GET","/users/\*/devices"})*/
      public function getUserDevices....

      /** @route({"GET","/catalogs/\*/Devices"})*/
      public function geCatalogDevices....
}

同时Users和Catalogs中其他方法的路由不变。phprs的路由是以方法为单位,而不是以类为单位的,路由搜索时优先匹配精度高的规则。

举例来说,如果存在Devices和Users两个类,分别定义了/users//devices和/users//info接口,那么/users/id/devices会命中Devices中的方法,/users/id/info会命中Users中的方法

@dearbird
Copy link
Author

dearbird commented Apr 7, 2016

作为轻量级的解决方案, 显然 @caoym 方案要好一些,但还是有一些问题。
以答复中Devices的例子, 如果path 指定为 “/”, 会导致后面每个方法的 route声明都要带 /devices

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants