Archive for the ‘Snippets Ideas’ Category
A straightforward way to translate your language files in CodeIgniter
Months ago we discussed about different alternatives to add i18n support to CodeIgniter applications. On this opportunity we will show how easy is to maintain your language files using CodeIgniter Language File Translator by MrKirkland and Owen Christian.
Basically what you need to do is download the zip here and then unpack the files under appropriate location, as explained in the article.
Afterward, create your desired language files languages folder. For example, if you would like to use English and Spanish, let’s say you create these two files:
- application/languages/spanish/general_lang.php
- application/languages/english/general_lang.php
You’d need to load that general language file in your controller or the autoload.php config file, and then choose which of these files you will use as Master file. That means the file that you will keep updated every time and use as reference when synchronizing with the other slaves files.
Then, you’ll need to run the new controller that was unpacked by pointing your browser to index.php/translator
You will be guided through the translator interface that will take care of your language strings under master and slave files. So, go to your slave files and translate each value.
In case any key in your slave file is not present under your master file, then you will see a mismatch error message warning about that behavior.
For non-english speakers: If you plan to use a different Master file rather than English, you can. In theory you’d need to edit the config file under /application/config/translator.php , but my last attempt did not work in version 0.5.1, For example, if I’d like to use Spanish as Master language instead of English, then I needed to edit the variable used in controllers/translator.php under line #87:
var $masterLang = 'spanish';
For more information, we strongly recommend to read the author’s article.
CodeIgniter in Spanish Language
CodeIgniter has been translated to many international languages, not only the User Guide but also the messages and errors strings in its language packs.
For example, you can find Spanish translations for your CodeIgniter applications, here. [Make sure to download the right version, ie: 1.7.2]
The next step once you unpack the .zip is to copy the files into your language directory that usually is located under /system/languages so it will read /system/languages/spanish
Then, to use Spanish messages in your applications you’ll need to chaneg the default language setting in /application/config/config.php under line $config['language']
Get Location Information based on an address, city or country name
In our last post we explained how to use GeoIP easily in CodeIgniter. Now we are interested in getting location information from a particular address using a Geocoder tool. For that reason, we’d recommend to take a look over How to use Google Maps API with PHP from Zimuel’s blog.
Zimuel exposes the following scenario:
Scenario: you have to check the validity of the geo data of a list of customers stored into a database. Using the Google Maps API you can easly compare the data stored into your database with the google data and fix the errors.
Moreover, his solution using Google Maps API proposes the following solution.
A PHP class that uses the Google Maps API to provide geographic information from a generic address (city, country, street+city, country. etc.).
So, based on that basis we would be interested in integrating this solution into CodeIgniter application. In order to do that, we can achieve the following steps:
1. Downloading the GMaps library from Zimuel’s blog.
2. Unpacking the zip and copy the GMaps.php file into your library directory: /application/libraries/GMaps.php
3. Put the content under example.php into your controller class where you are interested in using the Google Maps library. For example, you can use the following code to get information from a location assuming that $gmaps_key is your Google Maps key (get it from here for free), and $search is the variable containing the search string (ie: an address, a city, etc.:
$this->load->library('GMaps', $gmaps_key );
if ($this->gmaps->getInfoLocation( $search )) {
echo 'Address: '.$this->gmaps->getAddress().'';
echo 'Country name: '.$this->gmaps->getCountryName().'';
echo 'Country name code: '.$this->gmaps->getCountryNameCode().'';
echo 'Administrative area name: '.$this->gmaps->getAdministrativeAreaName().'';
echo 'Postal code: '.$this->gmaps->getPostalCode().'';
echo 'Latitude: '.$this->gmaps->getLatitude().'';
echo 'Longitude: '.$this->gmaps->getLongitude().'';
$this->data['lat'] = $this->gmaps->getLatitude();
$this->data['lng'] = $this->gmaps->getLongitude();
} else {
echo "The response of Google Maps is empty";
}
Finally, the text displayed in the page contains geo information such as latitude, longitude, postal code, country code and name, etc.
Using GeoIP in CodeIgniter application
The company called Maxmind published free resources to use Geo localized IP services in your web applications. I remember this service is there from long time ago.
Now, we are interested in getting geo information from users in a website, so it could be a good idea to integrate GeoIP services as a CodeIgniter plugin.
@Burak posted a short but nice article at phpandstuff.com explaining how to integrate GeoIP in a PHP script.
So, based on that article, I’d integrate the GeoIP as a plugin, by following these steps:
1. Create a new plugin file under application/plugins/geo_ip.php and I put there the content that is inside geoip.inc
2. We’d need to copy the GeoIP.dat file to any location inside our application. I used resources/geo/GeoIP.dat as location.
3. Then we’d need to load the plugin file, we can do that on any particular controller file (on demand) or we can add it as autoloaded plugin in application/config/autoload.php
4. I went to the controller class where I want to use GeoIP to grab the user’s country name and code, and put this snippet:
$gi = geoip_open('resources/geo/GeoIP.dat',GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
$this->data['country_code'] = $country_code;
$this->data['country_name'] = $country_name;
$country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']);
// close the database
geoip_close($gi);
That’s all, assuming that finally you will have the Country Code and Country Name under $this->data variable. You can see more info about why I use this way to pass information to view, under Using a Super Controller Class in CodeIgniter.
Fast way to randomly choose an Array item
When dealing with arrays in PHP, I usually need to choose a random item to display, for example an image that rotates randomly in a homepage or interior page, actually doesn’t matter which page.
The applications and needs may differ a lot, but here is a simple snippet that you can use to randomly select an item in a PHP Array.
Basically it uses array_rand() function.
For example, imagine we have the filenames for images that we want to rotate in a page (banners or whatever). Then I’ll define an array, and then I will use array_rand() to get a random key.
$headers = array("menu_header_1.jpg", "menu_header_2.jpg", "menu_header_3.jpg", "menu_header_4.jpg");
$value = $headers[array_rand($headers)];
How to Backup files using CodeIgniter
If you are developing a CodeIgniter application and need to backup files, let’s say in a .zip file, then you are lucky since CodeIgniter has a Zip Encoding library.
In my case, I used this library to create file backup, most of the time. But you can use it for other interesting things, for example adding string data to a .zip file and then allow users to download that file from a web page.
In this post I’ll only show the case we need to backup a directory using CodeIgniter and save the content to a .zip file.
Originally, this code read images and Flash files from the database and then save these images (binary data) into the file system. Since that action will run periodically using a Cron job, I’d like to do a backup for the existing files before overwriting. That’s where the Zip Class comes in action to compress a directory into an archive.
function _create_backup()
{
$this->load->library('zip');
$path = 'media/';
$this->zip->read_dir($path);
$result = $this->zip->archive('my_backup.zip');
return $result;
}
If you want the zip file to have a better name, probably you can add the current date as a suffix, so you can know where the file was created. To do that, you can replace ‘my_backup.zip’ by:
$result = $this->zip->archive('media_backup_'.date('Ymdhs').'.zip');
That will add the current date as a suffix.
Hope this snippet helps you the next time you need to backup files. If you are interested in other usages, you can refer to the CodeIgniter’s User Guide for more information.
How do I use Constants in CodeIgniter applications?
Usually I need to use constants or pass them as parameter in a function.
I don’t like the idea to hardcode these values in the code, nor sometimes I don’t like to use the PHP define() function to define constants since later it is a mass to search where a constant for a given entity has been defined.
Recently I started to use constants by defining these constants in a model Class (as reference you can find more info about Object Constants here).
Let’s say we have an Order_model class that manages Orders in an e-commerce application built in CodeIgniter. That Order_model class will implement the methods for create, update, list or view orders, for example.
Now, imagine we want to define simple states for each order. So, an order can be APPROVED as 1 or PENDING as 0.
A natural way to do that (wrong way IMHO) is to set the numeric value (1 or 0 in this case) hardcoded.
Instead of that, I created two object constants, as follows:
class Order_model extends Model {
var $tablename = 'Orders';
var $tablename_details = 'OrderDetails';
const ORDER_STATUS_PENDING = 0;
const ORDER_STATUS_APPROVED = 1;
Then, imagine we have an update_order_status() function in that model that will change the order status:
function update_order_status($order_id, $new_status)
Later, in the Controller class that will call this update function, I’ll use the constant in this way:
$this->order_model->update_order_status($order_id, Order_Model::ORDER_STATUS_APPROVED);
By doing that, the next time I need to change or maintain that code, I’ll go directly to the model class.
Unit Testing in CodeIgniter (Who use it?)
Using Unit tests is a best practice when developing software.
CodeIgniter has a Unit Testing class that is aimed to provide support for Unit Tests in your code.
Despite the CI Class for Unit Testing is quite simple, it may be very helpful to determine if what you are coding is exactly what you expect or not, by doing simple test cases.
I’d suggest to review their Unit Testing class.
The initialization of this library is quite simple simple, too. You just need to add the following line, and then the Unit Test object will be available using $this->unit.
$this->load->library('unit_test');
Once you loaded the library, you can start running simple tests. For each test, you specify the $test parameter (ie: 1+1), the expected result and the test name.
Also you can specify if a value is any of the available data types supported in the application, ie: is_string, is_bool, is_false, is_float, and so on, to evaluate if the result match with the expected data type.
Simple Shopping Cart in CodeIgniter
ExpressionEngine Dev Team is preparing a Cart library for CodeIgniter version 1.7.2
If you are interested in a preview of this CodeIgniter shopping cart, you can download the Cart.php from trunk, or you can wait until 1.7.2 is launched.
http://dev.ellislab.com/svn/CodeIgniter/trunk/system/libraries/Cart.php
The documentation is here:
http://dev.ellislab.com/svn/CodeIgniter/trunk/user_guide/libraries/cart.html
Things you can do with this Cart library
Add items to the cart. You use an array specifying id, quantity, price, name and a sub-array with options.
Add multiple items to the cart, at once. Similar to adding a single product but in this case you can specify an array of products.
Display the cart content. For this purpose, you will create a view file and use the Cart functions to retrieve the cart content, options and calculate totals.
Update the cart. For example, updates the quantity for an existing item insider your cart.
More inside this Cart
Then, you can other accessible functions that you can use, for example:
- Calculate the Total amount in the cart.
- Count the number of items in the cart.
- Return an array containing everything inside the cart.
- Return the options assigned for a particular product.
- Destroy the cart.
Use your Site URL or Base URL in Javascript functions
When writing AJAX applications with CodeIgniter, you usually want to post to a controller class by using Javascript functions. For example, if you are using jQuery for posting a form or loading back a page using an AJAX style, then you need to call the Controller class from your jQuery code.
Profiling your CodeIgniter applications
The CI Output Class has enable_profiler() to set enable the profiler in CodeIgniter.
By using this operation, you can enable or disable the profiler in the output.
$this->output->enable_profiler(TRUE);
The profiler is very useful for debugging purposes, you can see a footer with information all the time while running your application in development phase.
CodeIgniter and SEO
One of the powerful features of CodeIgniter is its great support for SEO purposes.
Titles, friendly URL are just an example of what you can do with CodeIgniter.
I’d recommend this excellent article from SEO Coding, explaining some CodeIgniter tips for SEO.
In addition, if you are optimizing your application for search engines, then you may be interested in removing index.php from the default installation of CodeIgniter application. You can do that by reading this article.
You also may be interested in reading this forum thread, explaining that controllers do not support dashes, so take that in mind when writing your own controllers in CodeIgniter. However, you can use custom Routes for routing URL friendly controller names to your existing controllers.
At URL Helper, you may find a great helper function for preparing titles for URLs, that’s good to optimize your titles for Search Engine Optimization.
$title = "My SEO title";
$url_title = url_title($title);
will produce this: My-SEO-title
$title = "My SEO title";
$url_title = url_title($title, 'underscore', TRUE);
will produce a different title using underscore and lowercase, like this: my_seo_title
How to submit a page to the same controller in CodeIgniter
Imagine you have a view with a <FORM> that need to submit to the same controller class. Probably you don’t want to hardcode the action attribute of your form nor leaving it in blank.
Using PHP_SELF could be a possible approach. However, since $_SERVER[‘PHP_SELF’] is a PHP server variable (nothing to do with CodeIgniter), you may encounter some problems with different environments.
So, why not to use the built-in CodeIgniter URI library? My solution to this problem is the following. Use $this->uri->uri_string() in conjunction with site_url().
Here is a simple example:
The easiest page dropdown list on CodeIgniter
Imagine you want to create a dropdown (or combo) to display numbers from a range of values, or page numbers from 1 to the total of pages.
With CodeIgniter and PHP, that is extremely easy. Here is an idea that may help you in some situations.
<?php echo form_dropdown('number', range(0,10) ); ?>
The line of code creates a <SELECT> control with the name number, and passing an array of values from 0 to 10. form_dropdown() is part of the CodeIgniter’s form helper, while range() is a PHP function that retrieves an array with a range of values.
Take in mind that form_dropdown can receive an assoc array of keys and values while in this example we are only passing an array of values. When passing an array of values, then the options will be numbered from 0 to N, so if you need options starting from 1 instead of zero, take in mind that probably you need to modify that line of code (using array_combine() may be useful).



