动作缓存 Caching an Action
显示静态信息以及从数据库读取信息的动作,都很适于缓存。显示静态信息的动作与数据库和会话无关,数据库读取信息的动作,只读取而不修改数据库,如GET请求。图 12-1 表明了这一情况下,动作的结果或者包括其布局都将被缓存。
Actions displaying static information (not depending on database or session-dependent data) or actions reading information from a database but without modifying it (typically, GET requests) are often ideal for caching. Figure 12-1 shows which elements of the page are cached in this case: either the action result (its template) or the action result together with the layout.
图 12-1 - 动作缓存 Figure 12-1 - Caching an action
例如,user/list(用户列表)动作返回网站的所有用户列表。除非用户被修改,添加或删除,否则列表将保持不变,因此很适宜缓存。 For instance, consider a user/list action that returns the list of all users of a website. Unless a user is modified, added, or removed (and this matter will be discussed later in the "Removing Items from the Cache" section), this list always displays the same information, so it is a good candidate for caching.
每个动作的缓存开启,在模块的config目录下的cache.yml文件中。举例如列表12-2: Cache activation and settings, action by action, are defined in a cache.yml file located in the module config/ directory. See Listing 12-2 for an example.
列表 12-2 - 开启动作缓存 (myapp/modules/user/config/cache.yml) Listing 12-2 - Activating the Cache for an Action, in myapp/modules/user/config/cache.yml
list:
enabled: on
with_layout: false # 默认值
lifetime: 86400 # 默认值
上述配置开启了list动作的缓存,布局不随动作一起被缓存(默认)。也就是说,即使动作缓存版本存在,布局(包括其局部模板和组件)仍然要执行。如果with_layou被设为true,布局将被缓存而不再重复执行。 This configuration stipulates that the cache is on for the list action, and that the layout will not be cached with the action (which is the default behavior). It means that even if a cached version of the action exists, the layout (together with its partials and components) is still executed. If the with_layout setting is set to true, the layout is cached with the action and not executed again.
测试缓存设置,从浏览器中调用开发环境的list动作: To test the cache settings, call the action in the development environment from your browser.
http://myapp.example.com/myapp_dev.php/user/list