Play! 2.0 Scala - Accessing global object

user375566 picture user375566 · May 4, 2012 · Viewed 7.9k times · Source

I've declared an object which gets instantiated on application start. I want to access it inside a controller, which is part of a plugin. I want to be able to use that plugin, but I can't seem to get past the first part -- finding the MyWebsocketConnection object. None of the examples show how to do this. I don't want to inject into the controller because I'm writing a plugin (I saw static examples of how to do that somewhere).

Global.scala, plugin application \app\Global.scala

object Global extends GlobalSettings {

  object MyWebsocketConnection {
    val logger = // return something that gets instantiated once, like websocket object for logging to ui
  }

  class MyWebsocketConnection {
    import MyWebsocketConnection.logger
  }

  override def onStart(app: Application) {
    Logger.info("Application has started...");
  }

}

My custom logging plugin controller:

MyLogger.Scala, plugin application \app\controllers\MyLogger.scala

object MyLogger {

  def info(message: String) = {
    // THIS CAN'T BE FOUND ?
    // MyWebsocketConnection.logger.send(message)
  }

}

So, from the Play! 2.0 app that references the plugin, I would (probably) do something like below, but I can't even get past the part before this:

MyFutureController.scala, another Play! application \app\controllers\MyFutureController.scala

object MyFutureController extends Controller {
  def someRandomMethod = Action {
    // Custom logging
    MyLogger.info("Here's my log message!");
    Ok("This documentation stinks!")
  }
}

Answer

Sasha O picture Sasha O · Jun 27, 2012

There is also workaround #3: move your Global class to a package and specify its fully qualified name in application.conf file, like so:

global= my.packaged.Global