A Varialbe in all Views

I want to extract a variable to all views. How can I do that ?

For example I want to extract variable $location to all views which is the location of current user ( by ip ).

$location = new Iplocation;

$ip = CHttpRequest::getUserHostAddress();

$ips = split("\.", "$ip");

$ip = $ips[3] + $ips[2]256 + $ips[1] * 256 * 256 + $ips[0] 256256256;

$location->findAllByAttributes(‘countrySHORT’, “$ip <= ipTO AND $ip >= ipFROM” );

where should I put above code ?


Override this action ( http://www.yiiframework.com/doc/api/1.1/CController#beforeAction-detail ) in your controller class (if you used gii, it should be in /protected/components)

You must add an new variable too and the assign the location by:

$this->loc = $loaction;

in your new beforeAction method :)

great answer … I’m new to yii. Thank you. works like a charm ;)

I would write a Geo Model with a static function which runs your code and caches the result. Then you can access the geo location data from anywhere in your code with Geo::getLocation(). I would certainly add caching, you don’t want to query the database on each request with static data like this. The simplest method to cache this, is to store the location in the session.

Thanks for your reply, I store location in a cookie and I’m not query database every single time, just the first time. Thanks for your tip.