我正在玩 Fantom 的 afBedSheet 框架,在它的文档中,例子是……
using afIoc
using afBedSheet
class HelloPage {
Text hello(Str name, Int iq := 666) {
return Text.fromPlain("Hello! I'm $name and I have an IQ of $iq!")
}
}
class AppModule {
@Contribute { serviceType=Routes# }
static Void contributeRoutes(OrderedConfig conf) {
conf.add(Route(`/index`, Text.fromPlain("Welcome to BedSheet!")))
conf.add(Route(`/hello/**`, HelloPage#hello))
}
}
...
当添加的路由越来越多时,尤其是当路由处理程序来自不同的类时,上面的contributeRoutes 方法开始变得难以阅读和维护。
我这样做的方式不同:在每个 Service 类上,我添加了一个静态方法,该方法返回由其方法处理的路由列表,如下例所示:
using afBedSheet
class Info {
static Route[] routes() {[
Route(`/info`, #all),
Route(`/info/pod`, #podAll),
Route(`/info/pod/name`, #podName),
Route(`/info/pod/version`, #podVersion),
]}
Text all() {
Text.fromJson(["This application blah blah blah"])
}
Text podAll() {
pod := Pod.of(this)
return Text.fromPlain("$pod.name $pod.version.toStr")
}
Text podName() {
Text.fromPlain(Pod.of(this).name)
}
Text podVersion() {
Text.fromPlain(Pod.of(this).version.toStr)
}
}
然后我的 AppModule 看起来像这样
using afIoc
using afBedSheet
class AppModule {
@Contribute { serviceType=Routes# }
static Void contributeRoutes(OrderedConfig conf) {
Info.routes.each { conf.add(it) }
AnotherService.routes.each { conf.add(it) }
YetAnotherService.routes.each { conf.add(it) }
...
}
我试图保持 AppModule 干净,并且 Route 定义和处理程序映射更接近实现类。我希望这会使服务/路由更易于维护,但我不确定这是一个好主意还是坏主意。我发现这样做的好处是
- 如果我向一个类添加路由处理程序方法,我在同一个类上声明路由
- 由于路由处理程序方法是同一个类的一部分,因此我只需要输入插槽名称(例如#podVersion 而不是 Info#podVersion),这对我来说似乎更容易阅读。
但正如我所说,我只是在玩 afBedSheet,如果有充分的理由在 AppModule 类中声明路由,我想从使用此框架完成实际生产项目的人那里知道,如示例所示.
此外,如果我正在做的事情是好的或好的,我想知道是否有(或者添加是否是一个好主意)方面将我上面的 Info 类更改为更像:
using afBedSheet
@Service // Assuming there is such facet to let afBedSheet discover services
class Info {
@Route { `/info` } // <- Route handler facet
Text all() {
Text.fromJson(["This application blah blah blah"])
}
@Route { `/info/pod` }
Text podAll() {
pod := Pod.of(this)
return Text.fromPlain("$pod.name $pod.version.toStr")
}
@Route { `/info/pod/name` }
Text podName() {
Text.fromPlain(Pod.of(this).name)
}
@Route { `/info/pod/version` }
Text podVersion() {
Text.fromPlain(Pod.of(this).version.toStr)
}
}
如果不存在这样的方面,我想一定有充分的理由在 AppModule 中保留路由声明,我想知道它们是什么。