jigniter™

jQuery & CodeIgniter – Perfect combination for web application

Archive for the ‘codeigniter’ tag

Using GeoIP in CodeIgniter application

with one comment

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.

Written byadmin

January 9th, 2010 at 9:07 am

How do I display result or error messages in CodeIgniter application

with 3 comments

Sometimes we need to display general messages or error messages to the user noticing about certain action, for example on success or failure.

Imagine you are submitting a form and then creating or updating the data in the database. You may be interested in noticing the user about the result for that action.

This is the way I use to display general messages (and error messages) in CodeIgniter application.

The result

This is how my message looks.

codeigniter-display-message

How to display the message?

Now, in order to display that information message, I do the following:

First, when submitting the form, after validating it, in the controller I call the model function that will save the entity (license in this case). I make sure that model function returns a result, and FALSE result in case of error (I usually return an array result on success with an ID element with the last inserted identifier if the result was an insert, or the just updated entity identifier if it was an update, but that is out of this article’s scope).

Controller

Imagine we are calling the following method in the controller:

$result = $this->license_model->create_or_update_license($agent_id, $state, $data);

Then, we need to see if that was an error or not. Based on that result, I will use CodeIgniter’s set_flashdata function in the Session library, as follows:

if ($result)
{
	$this->session->set_flashdata( 'message', array( 'title' => 'License created', 'content' => 'License has been saved sucessfully', 'type' => 'message' ));
	redirect('agent/licenses');	

} else
{
	$this->session->set_flashdata( 'message', array( 'title' => 'License error', 'content' => 'License could not be saved', 'type' => 'error' ));
	redirect('agent/licenses');
}

Once the Flash message has been set, I redirect the user to the form or a list of results. That is needed in order to get the flash working (you cannot just load the view in this case… well, you can but this method will not work in such case). When comparing $result TRUE or FALSE, please notice the different value for type. I am using type=message for successful messages, and type=error for error mesages.

View

In the view, just above the form, I use this snippet.



<?= @flash_message() ?>

To keep it simple, I just added @ to avoid any error message, but probably if you are looking for a better coding practice and you may not do that.

A Helper

Then, I put this flash message function as a helper function, so it is available when calling from the view.


function flash_message()
{
	// get flash message from CI instance
	$ci =& get_instance();
	$flashmsg = $ci->session->flashdata('message');

	$html = '';
	if (is_array($flashmsg))
	{
		$html = '<div id="flashmessage" class="'.$flashmsg[type].'">
			<img style="float: right; cursor: pointer" id="closemessage" src="'.base_url().'images/cross.png" />
			<strong>'.$flashmsg['title'].'</strong>
			<p>'.$flashmsg['content'].'</p>
			</div>';
	}
	return $html;
}

jQuery part

Finally, I added a simple effect to slide down and blink the message box, and adding the close functionality with a simple jQuery function. You can do something like this. Of course, you can modify it or just avoid using the jQuery effect if it is desired.


// first slide down and blink the message box
$("#flashmessage").animate({top: "0px"}, 1000 ).show('fast').fadeIn(200).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

Some CSS styling

Finally, just add some CSS styling for #flashmessage, using message or error class names.


.message{
    border:1px solid #CCCCCC;
    width:300px;
    border:1px solid #c93;
    background:#ffc;
    padding:5px;
    color: #333333;
    margin-bottom:10px;
}

Enjoy it.

Written byadmin

September 18th, 2009 at 11:49 pm

Posted inTutorials

Tagged with , , ,

How do I use Constants in CodeIgniter applications?

without comments

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.

Written byadmin

August 28th, 2009 at 5:19 pm

Posted inSnippets Ideas

Tagged with ,

Profiling your CodeIgniter applications

without comments

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.

Read the rest of this entry »

Written byadmin

August 14th, 2009 at 10:47 am

Posted inSnippets Ideas

Tagged with , ,

CodeIgniter and SEO

without comments

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

Written byadmin

August 12th, 2009 at 2:48 pm

Posted inSnippets Ideas

Tagged with ,

Simple Form Generation in CodeIgniter

with 7 comments

If you are using CodeIgniter, as well as any other PHP framework, you may notice that building CRUD forms is one of the most bother and routine tasks. Probably 80% of general web applications uses CRUD (create/read/update/delete).

In CodeIgniter, you can use any of the form generation libraries.

One of my preferred libraries is Form Generation Library by Frank Michel (see @macigniter’s thread here). It allows you to create clean XHTML forms with CodeIgniter. See demo here.

Using Form Generation Library

So, in order to use this library, you need to download it from here (library files only is enough if you don’t want the entire site structure).

Read the rest of this entry »

Written byadmin

August 2nd, 2009 at 6:30 pm

Posted inTutorials

Tagged with , ,

Remove index.php from URL

with 9 comments

CodeIgniter is designed to be search-engine and human friendly. By default, index.php will be included in the URLs, but it can be easily removed using .htaccess file with some rules.

Read the rest of this entry »

Written byadmin

July 25th, 2009 at 2:28 pm

Posted inTutorials

Tagged with

Fix Session problem when upgrading to CI 1.7.1

without comments

If you encountered the following problem when upgrading from CodeIgniter 1.6.x to 1.7.x, then here is a workaround.

A PHP Error was encountered

Severity: 4096

Message: Object of class stdClass could not be converted to string

Filename: libraries/Session.php

Line Number: 715

A quick fix can be made by overriding Session class. As exposed at this forum thread, you can create MY_Session.php and place it under your libraries folder (When you place MY_ prefix, the class is automatically loaded).

Written byadmin

July 25th, 2009 at 12:05 pm

The importance of a well-documented framework

without comments

At the time to choose for a framework, evaluating the documentation is a crucial step in that decision.

I remember the time I chose CodeIgniter as framework I researched many of the features compared with other frameworks like Kohana and CakePHP, before taking the final opinion.

Later, I found that the documentation as well as online community were one of the most important decisions when choosing for a framework.

Read the rest of this entry »

Written byadmin

July 25th, 2009 at 11:31 am

Posted inUncategorized

Tagged with

Learning CodeIgniter PHP Framework

without comments

CodeIgniter is a great PHP framework, well-documented and very easy to learn for developers that already used other frameworks such as Symfony, CakePHP, Zend or PHP from scratch.

Organizing stuff to read

If you are interested in learning CodeIgniter, I’d recommend the following resources:

  • CodeIgniter User guide. This is a must-read documentation for any new developer interested in CodeIgniter. By opening the Table of Content you can go chapter-by-chapter understanding the following concepts:
    • Server requirements and installation.
    • Getting started, CodeIgniter at a Glance, Supported features, Application Flow Chart to understand the application flow, MVC to understand Model-View-Controller design pattern if you are new to object oriented programming or patterns, and architectural goals.
    • General Topics. Here you can find information regarding how CodeIgniter works, PHP Style Guide, Writing Documentation standard, Security topics, Libraries and more.
    • Class Reference. Including dozens of classes that you need to understand which functions exposes.
    • Helper Reference. Introduces many helpers that may speed or boost your development process.

Learning by examples

Looking for examples may help you to learn CodeIgniter.

Setting up Codeigniter, as seen in If Only I Knew That! blog. Step by step guide that shows you how to setup a CodeIgniter installation and

A Gentle Introduction to CodeIgniter, from EEInsider, explains how MVC design pattern works in CI (controller, models and views).

Getting started with CodeIgniter, from IBM, explains how to create MVC applications quickly and easily.

From my point of view, the first time I learned CodeIgniter was reviewing the source code of BambooInvoice, an open source invoicing application (created by Derek Allard).

Other resources

Here is a list of additional resources that may help you in the process of learning CodeIgniter framework. TheFuzzOne published here a list of resources with tutorials and information for newbies as well as intermediate developers.

The forum is a key resource too, on CodeIgniter forum you can find solutions to common problems. It is recommended to search for an specific problem/solution before asking a new question or opening a new thread, since most of the typical problems new developers have, are actually resolved and explained with a solution.

Probably one of the most used and useful threads there is the Code and Application Development thread.

MVC and CRUD related threads.

Written byadmin

July 15th, 2009 at 11:53 am

Posted inTutorials

Tagged with