2016-10-01 136 views
2

我有一个控制器,其中有一个构造函数,我在注入一个缓存,但是我想在实例创建时调用构造函数中的一个方法。我知道我们可以创造一些辅助的构造与构造函数中的调用方法

def this(foo:Foo){} 

但在我的情况下,因为是游戏框架一个实例我的引导是更复杂一点。

这里我的代码

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) 
    } 
    } 

我想的是,loadGameIds会被调用,当类实例化缓存。

有什么建议吗?

问候。

回答

5

如果我正确理解你的问题,你只是想添加一些语句到主构造函数体?如果是这种情况,您可以简单地在本身中这样做。在你的情况,应该是这样的:

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 => 
    ... 
    } 

    ... 
} 

这样做时,它通常是在类的所有瓦尔斯和VAR的声明之后进行额外的代码一个好主意,以确保它们是正确的在您的附加构造函数代码运行时初始化。

+0

非常感谢我尝试的对象init {loadGameIds}但没有。奇怪的是,我没有在我读过的任何博客中了解到这一点。 – paul

相关问题