Code snippets for symfony 1.x

Navigation

Google analytics code by filter

This simple filter automatically adds google analytics code for all pages. It's no longer required to modify all the layouts, just put google code to app.yml and this filter does everything for you.

Create a lib/filters/gaFilter.class.php file:

<?php
class gaFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // Nothing to do before the action
    $filterChain->execute();
    // Find google code and check if current module is not disabled
    if(($gaCode = sfConfig::get("app_ga_code",false)) !== false
    && !in_array($this->getContext()->getModuleName(),sfConfig::get("app_ga_disabled_modules",array()))) {
      //Decorate the response with the tracker code
      $response = $this->getContext()->getResponse();
      $response->setContent(str_ireplace('</body>', $gaCode.'</body>',$response->getContent())); 
    }
   }
}
 

Add the filter to filters.yml :

# insert your own filters here
 
# Google analytics filter
ga_filter:
  class: gaFilter
 

Now you are able to insert GA code into your page. Simply copy the whole code and add it as ga_code option into your app.yml file:

all:
  ...
  ga:
    code: >
      <script type="text/javascript">
      try {
      var pageTracker = _gat._getTracker("...");
      pageTracker._trackPageview();
      } catch(err) {}</script>
 

It works on fact, that you probably will not have a </body> tag in other place except at the end of your page and you will not use it in other content type than text/html.

Optionally you may disable GA filter in specific modules, such as administration is. To do this, add this option to your app.yml:

all:
  ...
  ga:
    disabled_modules: [administration]
    code: >
      ...
 
by Radek Petráň on 2010-03-07, tagged analytics  filter  google