【问题标题】:Minimize calls to controller from SilverStripe template最小化 SilverStripe 模板对控制器的调用
【发布时间】:2016-02-04 17:35:59
【问题描述】:

在我正在创建的Silverstripe 应用程序中,我有NewsArticles,其中有NewsTags(使用silverstripe-tagfield 创建)。我正在使用NewsTags 在每个NewsArticle 的侧边栏中创建一个“相关新闻”小部件。我在NewsArticle 控制器中创建了一个RelatedArticles 操作,一切正常。

但是,为了使用RelatedArticles 操作,我不得不调用该函数三次。不是一个大问题,但我想尽量减少调用多次调用数据库的函数的次数。

这是我的RelatedNewsModule.ss 模板文件的精简版:

// First call to check if there are related articles
<% if $RelatedArticles %>

    // second call to get the array
    <% loop $RelatedArticles() %>
        ...
    <% end_loop %>

    // third call to check if there are more than one so we need navigation
    <% if $RelatedArticles.Count > 1 %>
            ... navigation markup
    <% end_if %>

<% end_if %>

我想调用一次该函数,并可能使用 SilverStripe 模板中的属性,这些属性将引用两个检查和文章数组。不过我不知道该怎么做。

处理这种情况的最佳方法是什么?

【问题讨论】:

  • 循环中不需要括号。通常它应该缓存查询,所以if $RelatedArticlesloop $RelatedArticles,至少对于$has_many 或$many_many 关系。在您的情况下,您将在您的操作中手动缓存它。另见docs.silverstripe.org/en/3.1/developer_guides/performance/…
  • 对哦。我将删除括号并查看。根据缓存,我问这个问题的原因是因为我注意到在调试它时 var_dump 被调用了 3 次。
  • 好吧,您需要检查数据库是否被查询了 3 次或是否被缓存。只需将 ?showqueries=1 放入您的 URL。见docs.silverstripe.org/en/3.2/developer_guides/debugging/…
  • @rath3r 始终防止不必要的查询的最简单方法是将部分缓存与聚合一起使用。 docs.silverstripe.org/en/3.2/developer_guides/performance/… 只有在需要失效时才会这样做。
  • 例如,将昂贵的查询缓存到它自己的块中,检查计数,或者你想要聚合它的任何值。我当然不会通过 db 连接来检查值,但它们在 sql 中运行速度非常快。获取完整数据和操纵显示通常会导致性能下降。

标签: php silverstripe templating


【解决方案1】:

正如 cmets 中所说,SilverStripe 应该只调用一次数据库,并为接下来的 2 次调用缓存 RelatedArticles 结果。

为了进一步缓存查询,我们可以使用Partial Caching 来缓存模板的部分内容。

<% cached 'RelatedArticles', $ID, $List('RelatedArticles').max('LastEdited'), $List('RelatedArticles').count() %>
    <% if $RelatedArticles %>

        // second call to get the array
        <% loop $RelatedArticles %>
            ...
        <% end_loop %>

        // third call to check if there are more than one so we need navigation
        <% if $RelatedArticles.Count > 1 %>
            ... navigation markup
        <% end_if %>

    <% end_if %>
<% end_cached %>

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多