简体   繁体   中英

Add the same calculated property to every Symfony2 Controller in bundle

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 :\\

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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