在Play中定义全局变量的最佳方法! 2.0应用 [英] Best way to define globals in a Play! 2.0 application
问题描述
正在播放! 2.0,则可以按照此处中的说明使用Global
. Global
必须位于默认(空)程序包中.
In Play! 2.0, one can use Global
as documented here. Global
needs to be in the default (empty) package.
我的应用程序中也需要全局变量,并且其中的一些需要对Global
中的方法可用.因此,我将它们放在Global.scala中,如下所示:
I also need globals in my application, and some of them need to be available to the methods in Global
. Thus, I put them in Global.scala like so:
package object globals {
lazy val foo = Play.maybeApplication.flatMap(_.configuration.getString("foo")).getOrElse("default_value_of_foo")
}
然后我像这样在控制器中使用它:
And then I use it in my controllers like this:
globals.foo
有更好的方法吗?
推荐答案
我认为这个问题更多的是关于通用软件设计,而不是关于Play框架.如果您确实需要一堆随机属性,为什么不创建自己的对象?
I think this question is more about general software design than it is about Play Framework. If you truly need a bunch of random properties why not create your own object?
object Configuration {
val timeout = Play.maybeApplication.flatMap(
_.configuration.getString("timeout")
).getOrElse(0))
}
但是通常这些值属于正在配置的其他逻辑实体.
But usually the values belong to some other logical entity that is being configured.
这篇关于在Play中定义全局变量的最佳方法! 2.0应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!