简体   繁体   English

PlayFramework实例化当前请求范围内的对象?

[英]PlayFramework instantiate object in current request scope?

I am currently active PlayFramework learner who came from world of PHP. 我目前是PlayFramework的活跃学习者,来自PHP领域。

For example I have a Head block object in my app, which should hold title, charset encoding, meta information, etc. Something similar to Magento blocks, but without XML declaration 例如,我的应用程序中有一个Head块对象,该对象应该包含标题,字符集编码,元信息等。类似于Magento块,但没有XML声明

package blocks.Page

object Head {
  var title: String = "";
}

In Application.index() method I have 在Application.index()方法中,我有

blocks.Page.Head.title
Ok(views.html.application.index());

And finally in html template 最后在html模板中

@import blocks.Page.Head
<title>@Head.title</title>

However, blocks.Page.Head object is defined for entire application scope, not for single request. 但是,blocks.Page.Head对象是为整个应用程序范围而不是单个请求定义的。 This object is the same for each request. 每个请求的对象都是相同的。

What is the right way to do, what I am trying to do? 正确的做法是什么,我正在尝试做什么? I can create container with all blocks and instantiate it with each request, then just pass to all templates. 我可以创建包含所有块的容器,并在每个请求中实例化它,然后将其传递给所有模板。 But I have a feeling that this is wrong way. 但是我感觉这是错误的方式。

Just use usual class instead of object and pass instance to template as parameter. 只需使用常规类而不是对象,然后将实例作为参数传递给模板。

Like this: 像这样:

package blocks.Page

case class Head(title: String = "")

Controller: 控制器:

val head = Head("Blah")
Ok(views.html.application.index(head))

And template will looks like: 模板将如下所示:

@(head: blocks.Page.Head)

...
<title>@head.title</title>

I know the feeling when coming from a request-oriented language like PHP :). 我知道来自像PHP的面向请求的语言时的感觉:)。 However, consider application-wide access as a gift of a VM (in PHP we need to go the extra mile of using some bytecode and data caching tool like APC or eAccellerator). 但是,将应用程序范围的访问视为VM的礼物(在PHP中,我们需要花更多精力使用一些字节码和数据缓存工具,例如APC或eAccellerator)。

I would probably create a blockManager class which gives you static access to blocks by name/tag/id from the template: Block.get("MyBlock") . 我可能会创建一个blockManager类,该类使您可以从模板中通过名称/标签/ id静态访问块: Block.get("MyBlock") Then you can define and later modify your caching / storing strategy (holding in memory vs. loading from storage) without affecting your templates. 然后,您可以定义并稍后修改缓存/存储策略(保留在内存中还是从存储中加载),而不会影响模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM