drbvm26000 2013-09-10 16:01
浏览 25
已采纳

将相同的计算属性添加到bundle中的每个Symfony2 Controller

I'm converting an application over from a legacy framework to Symfony2. One of the things the app has is a tiny little message in the bottom corner of the rendered page that says

served by appserver3 in 200ms

or similar. It changes depending on the appserver you're on and the amount of time it took to serve the request. The value for the appserver is set in a config file (but that's largely irrelevant here).

Should I create a BaseController type class that extends Controller and then have all my controllers extend that? If so, how would I go about making sure that the BaseController always adds the responseTime and appServerName to the list of variables that will be passed to my twig template without having to add it manually in every controller like this:

// e.g. src/MyNamespace/MyBundle/Controller/AboutUsController.php
return $this->render('MyNamespaceMyBundle:Default:index.html.twig', array('var1' => $var1, 'appServerName' => $this->getAppServerName(), 'responseTime' => $this->getResponseTime()));

(Obviously this would assume that I created the getAppServerName and getResponseTime methods in my BaseController.)

This seems like a lot of copypasta and my whole reason for moving to Symfony2 is to avoid that :\

  • 写回答

1条回答 默认 最新

  • dongzhong3688 2013-09-10 16:28
    关注

    Solution 1

    For dynamic parts in the templates, especially in the base templates which are extended from every template, you can render the output from a controller action. It's like twigs include but it includes the dynamic content returned.

    See Embedding Controllers in the documentation.

    Outputting the served appserver is easy. Simply get the parameter from container. Calculating the load time may be a more complicated task and not really necessary for the user.

    Solution 2

    If it's only a static appserver parameter configured in your parameters.yml you can define it as a twig global variable in your config.yml:

    twig:
         globals:
             appserver: "%appserver%"
    

    Now you can include it in the needed twig template:

    serverd from {{ appserver }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值