Although everyone can copy/paste their Google Analytics code straight from the Google Analytics support section, it’s essential you create a generic function, that you can (re)use over and over until Google improves their code.

Luckily Zend Framework has something nifty called a view helper. With these view helpers, you can create simple classes that work with your Zend Framework view object while keeping your logic separate and maintainable.

<?php
class Application_View_Helper_GoogleAnalytics extends Zend_View_Helper_Abstract
{
    public $view;

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }
    public function googleAnalytics($trackerCode = null)
    {
        $html = null;
        if (null !== $trackerCode) {
            $html = $this->view->inlineScript()->appendScript(<<<EOS
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "https://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
EOS
            );
            $html = $this->view->inlineScript()->appendScript(<<<EOS
try{
var pageTracker = _gat._getTracker("{$trackerCode}");
pageTracker._trackPageview();
} catch(err) {}
EOS
            );
        }
        return $html;
    }
}

Now that you’ve got your analytics code in a view helper, you can easily call it from your bootstrapper to initialize it with your tracker code.

But you’re not just interested in who’s visiting your site, right ? For instance, all external links should be tagged to know people are exiting your website and for which links. That’s why another view helper should be made to track external links. Here’s an example.

<?php
class Application_View_Helper_ExternalLink extends Zend_View_Helper_Abstract
{
    const CAMPAIGN_SOURCE = 'blogpost';
    const CAMPAIGN_MEDIUM = 'website';
    const CAMPAIGN_TERM = 'zend%20framework%20tutorial';
    const CAMPAIGN_CONTENT = 'text_link';
    const CAMPAIGN_NAME = 'communityworks';

    public $view;

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }
    public function externalLink($href, $text = null, $linkOnly = false)
    {
        if (is_array ($href)) {
            $params = $href;
        }
        if (is_string($href)) {
            $params = array ();
            $params['href'] = $href;
            if (null !== $text) {
                $params['text'] = $text;
            }
        }
        if (!is_array ($params)) {
            throw new Zend_View_Exception(
            	'ExternalLink view helper requires an array of params');
        }
        $params = new ArrayObject($params, ArrayObject::ARRAY_AS_PROPS);
        if (!isset ($params->href)) {
            throw new Zend_View_Exception(
            	'ExternalLink requires the 'href' param to be set');
        }
        if (!isset ($params->text)) {
            $params->text = $params->href;
        }
        if (!isset ($params->title)) {
            $params->title = $params->text;
        }
        if (!isset ($params->rel)) {
            $params->rel = 'nofollow';
        }
        if (!isset ($params->utm_source)) {
            $params->utm_source = self::CAMPAIGN_SOURCE;
        }
        if (!isset ($params->utm_medium)) {
            $params->utm_medium = self::CAMPAIGN_MEDIUM;
        }
        if (!isset ($params->utm_term)) {
            $params->utm_term = self::CAMPAIGN_TERM;
        }
        if (!isset ($params->utm_content)) {
            $params->utm_content = self::CAMPAIGN_CONTENT;
        }
        if (!isset ($params->utm_name)) {
            $params->utm_name = self::CAMPAIGN_NAME;
        }
        $link = $params->href  . '?'
              . 'utm_source='  . $params->utm_source . '&'
              . 'utm_medium='  . $params->utm_medium . '&'
              . 'utm_term='    . $params->utm_term . '&'
              . 'utm_content=' . $params->utm_content . '&'
              . 'utm_name='    . $params->utm_name;
        if (true === $linkOnly) {
            return $link;
        }
        $qa = "_gaq.push(['_trackEvent', 'Website', 'Link', '{$params->text}']);";
        return sprintf('<a href="%s" title="%s" onClick="%s" rel="%s">%s</a>',
            $link,
            $params->title,
            $qa,
            $params->rel,
            $params->text
        );
    }
}

And all you need to do now is open a view template that contains an outgoing link and you can immediately replace it with your new view helper.

Example:

<a href="https://in2it.be" title="in2it vof website">in2it vof website</a>

becomes in your view

<?php echo $this->externalLink('https://in2it.be', 'in2it vof website'); ?>

The generated HTML will contain the following

<a href="https://in2it.be/?utm_source=blogpost&utm_medium=website&utm_term=zend%20framework%20tutorial&utm_content=text_link&utm_name=communityworks" title="in2it vof website" onClick="_gaq.push(['_trackEvent', 'Website', 'Link', 'in2it vof website']);" rel="nofollow">in2it vof website</a>

That’s it. With only 2 view helpers you can generate detailed analysis of visits on your website.

Categories: Buzz

Michelangelo van Dam

Michelangelo van Dam is a senior PHP architect, PHP community leader and international conference speaker with many contributions to PHP projects and community events.

2 Comments

coattyaccix · 19/02/2011 at 17:22

Sorry for the stupid question. What is the best search engine http://google.com or http://yahoo.com?

    michelangelo · 22/02/2011 at 12:17

    The best search engine is the one that gives you the results you want, even if it’s your own system. But for analytics, google has the widest range of tracking and reporting tools.

    But again, it’s your choice to make the decision.

Comments are closed.