I'm a RoR developer and I'm beginning with Yii. I want to create what I would call (as a RoR dev) a helper to display Google Analytics tracking code on my page. To be reusable I need only one param, the trackerId (ex "UI-3438-34").
Should I use a widget or a simple "helper" ? My helper can render a view like a widget ?
Thanks, I know I can add my analytics tracking code into my layout but I want to avoid having a lots of JS directly in my layout, for code clarity I prefer using helper / widget.
The question is still open even if my example is not good, the main problem is when to use helper and when to use widget.
As far as I know, Yii doesn’t have view helpers implemented in terms you mean it. However, it offers a good way to insert html tags for forms (have a look at CHtml class).
Widgets are often used to represent repeated small UI interfaces. (Like as Wordpress uses its internal sidebar widgets.)
You are recommended to create a widget for GA code, but also keep in mind, that if a single tracking code in your layout reduces code readability, you probably use far more JS code than you should.
(I’ve seen you’re not about to hardcode the tracking ID. I would’ve suggested that too.)
The class prefix is something that should be reserved for Yii classes. There’s nothing wrong with the class name you used, it’s only a recommended convention.
The closing php tag should be omitted. It is always better to be prepared.
Anyhow, I feel that this solution is a bit too complicated. But apparently it works.
Take a look at the portlets created in the blog demo.
You may not need the Porlet class demonstrated there – instead just inheriting from CWidget – but that will give you a lot of functionality that you might choose to use.
I would say “the Yii way” in this case is to create a widget. There’s tons of things you can add to your tracking component later on so it’s a good thing to have it in a place where you can extend it.
Here’s a very simple, straight forward example with what you seem to want:
Add your tracking code to "config/params.php"
Create the Google Analytics widget (components/GoogleAnalytics.php):
<?php
class GoogleAnalytics extends CWidget {
public function run() {
$this->render('tracking', array('id' => Yii::app()->params['google.analytics']);
}
}
?>
Add the javascript into it’s view (components/views/tracking.php):