Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method in constructor

I have a Controller with a constructor where I´m injecting a cache, but also I would like to invoke a method in the constructor when the instance is created. I know we can create some auxiliary constructors with

def this(foo:Foo){}

But in my case because is play framework the one that instance my bootstrap is a little bit more complex.

Here my code

class SteamController @Inject()(cache: CacheApi) extends BaseController {

  private val GAME_IDS_LIST_API: String = "api.steampowered.com/ISteamApps/GetAppList/v2"

  private val GAME_API: String = "store.steampowered.com/api/appdetails?appids="

  private val GAME_KEY: String = "games"

  def games = Action { implicit request =>
    var fromRequest = request.getQueryString("from")
    if (fromRequest.isEmpty) {
      fromRequest = Option("0")
    }
    val from = Integer.parseInt(fromRequest.get) * 10
    val to = from + 10
    loadGameIds()
    Ok(html.games(SteamStore.gamesIds(cache.getVal[JSONArray](GAME_KEY), from, to), cache.jsonArraySize(GAME_KEY)/10))
  }


  private def loadGameIds(): Unit = {
    val games = cache.get(GAME_KEY)
    if (games.isEmpty) {
      get(s"$GAME_IDS_LIST_API", asJsonGamesId)
      cache.set(GAME_KEY, lastResponse.get, 60.minutes)
    }
  }

What I would like is that loadGameIds would be invoked and cached when the class is instantiated.

Any suggestion?

Regards.

like image 224
paul Avatar asked Jul 06 '26 20:07

paul


1 Answers

If I understand correctly your question, you simply want to add some statements to the main constructor body? If that's the case, you can simply do so in the body of the class itself. In your case, that would look like this:

class SteamController @Inject()(cache: CacheApi) extends BaseController {

  ...

  private val GAME_KEY: String = "games"

  loadGameIds() // <-- Here we are calling from the main constructor body

  def games = Action { implicit request =>
    ...
  }

  ...
}

When doing so, it is usually a good idea to perform additional code after the declaration of all vals and vars in your class, to ensure they are properly initialized at the time your additional constructor code runs.

like image 167
sjrd Avatar answered Jul 10 '26 15:07

sjrd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!