skip to content

Zend Framework View Helper pour Google Analytics

Un View Helper dans le Framework Zend permet de créer des scriptes qui afficheront ensuite facilement un bout de code HTML grâce à l'objet Vue.

Voici un exemple de ViewHelper pour afficher le script GoogleAnalytics avec une option pour le funneling :

<?php
/**
* View Helper to create the GoogleAnalytics javascript
*/
class BP3_ViewHelper_GoogleAnalytics extends Zend_View_Helper_Abstract
{
public $view;

public function setView(Zend_View_Interface $view)
{
$this->view = $view;
}


/**
* Create the GoogleAnalytics javascript
* @param option string $funnel like "/funnel_G1/step1.html"
* @param option string $id of the GoogleAnalytics account
*
* @return void display the javascript with zend_view::inlineScript()
*/
public function GoogleAnalytics($funnel=null, $id="UA-423998-9")
{
$this->view->inlineScript()->captureStart(); ?>
var gaJsHost = (("https:" == document.location.protocol) ?
"https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost
+ "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
<?php $this->view->inlineScript()->captureEnd();

$this->view->inlineScript()->captureStart(); ?>
var pageTracker = _gat._getTracker("<?php echo $id; ?>");
pageTracker._trackPageview(<?php echo ($funnel)?'"'.$funnel.'"':null; ?>);
<?php $this->view->inlineScript()->captureEnd();
}
}

Nous devons dans un premier temps initialiser ce helper dans notre application. Pour cela on nomme le fichier contenant le scripte ci-dessus du même nom que la classe (soit "ViewHelper_GoogleAnalytics.php" dans notre exemple) puis on met ce fichier dans un répertoire et on annonce ce répertoire au Zend Framework grâce à la commande :

$view->addHelperPath('./mon/repertoire/viewHelper', 'AidesDeVue');

Pour afficher le Javascript GoogleAnalytics on utilise inlineScript() du Zend Framework et le bout de code suivant doit se trouver juste avant la balise </body> de votre template :

...
<?php echo $this->inlineScript(); ?>
</body>
</html>

On y est presque ! Il suffit maintenant depuis notre scripte de vue d'appeler le helper pour afficher votre code GoogleAnalytics.

$view->GoogleAnalytics();

Si je fais du funneling, je peux rajouter le chemin de ce dernier dans mon script et aussi changer le numéro d'identifiant GoogleAnalytics au besoin :

$view->GoogleAnalytics("/funnel_G1/step1.html", "UA-123456-2");

Simple mais efficace une fois mis en place !

Powered by Drupal. CrystalX theme created by Nuvio | Webdesign.