Simple Google Analytics View Helper
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 42 43 44 4546 47 48 49 5051 52 53 54 5556 57 58 59 6061 62 63 64 6566 | <?php /** * Google Analytics Javascript View Helper * * @copyright Copyright (c) 2008-2009 Pro Soft Resources USA Inc. (http://www.prosoftpeople.com) * @author Rolando Espinoza La fuente (darkrho@gmail.com) * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @version $Id$ */ class View_Helper_Analytics extends Zend_View_Helper_Abstract { /** * @var string Google Analytics Javascript */ protected $_script = null; /** * @var string Google Analytics Code */ protected $_gaCode = null; /** * Constructor: * - checks GA code is set in config registry * - setup GA javascript * */ public function __construct() { if (Zend_Registry::isRegistered('config')) { $config = Zend_Registry::get('config'); if (isset($config->google->analytics->code)) { $this->_gaCode = $config->google->analytics->code; } } $this->_script = <<< END <script type="text/javascript"> 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")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker(":code");pageTracker._trackPageview(); } catch(err) {} </script> END; } /** * Returns javascript GA script if GA code is set * * @return string */ public function analytics() { if (null != $this->_gaCode) { return str_replace(':code', $this->_gaCode, $this->_script); } else { return ''; } }} |
Comments
Hi, thanks for your comment.
I thought the same, but as i use multiple instance with the same code base, i use configuration file to enable google analytics.
I'll add optional parameter in the next version to override Zend_Config.
You must login before commenting on a snippet. If you do not have an account, please register.
Snippet description
This view helper displays google analytics javascript code. If you need more funcionality checkout this snippet: http://zfsnippets.com/snippets/view/id/30
Example setup:
// in your config ini file
google.analytics.code = "UA-1234-1"
// some where in your bootstrap
$config = new Zend_Config_Ini(APPLICATION_PATH . '/config/app.ini', APPLICATION_ENV);
Zend_Registry::set('config', $config);
Snippet details
- Created:
-
Rho
- Edited:
-
Rho
- Revision Id:
- 18
- Edit Message:
- Initial Release
- Tags:
- view helper google analytics
- Comments:
- 4
- Views:
- 286
- Points:
- 0 (0 votes)
1 year ago
You don't need the Zend_Config dependence... I guess is better pass the GA code as a param to analytics() method, so is possible to use some config entry in the helper call (or just a string, etc). Hope this is useful :)