opyate
opyate

Reputation: 5428

Best way to define globals in a Play! 2.0 application

In Play! 2.0, one can use Global as documented here. Global needs to be in the default (empty) package.

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

Is there a better way?

Upvotes: 3

Views: 771

Answers (2)

Mirko Adari
Mirko Adari

Reputation: 5103

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.

Upvotes: 1

kheraud
kheraud

Reputation: 5288

I had problems using Global as a singleton for my app. I think you will have some problems too to access the singleton from your controllers (see this post).

But you can create your own singleton in one of your packages and access it as you plan to do.

Upvotes: 0

Related Questions